第5章 解構(gòu):使數(shù)據(jù)訪問更便捷
1.對象解構(gòu)
- 允許默認(rèn)值
let node = {
name: 'ylz',
age: 20
}
let {name, age, value = true} = node;
console.log(name); // ylz
- 為不同名局部變量賦值
let node = {
name: 'ylz',
age: 20
}
let {myName: name, myAge: age} = node;
console.log(myName); // ylz
- 嵌套對象解構(gòu)
let node = {
name: 'ylz',
age: 20,
son: {
msg: {
name: '233'
}
}
}
let {son: {msg}} = node;
console.log(msg.name); // 233
2.數(shù)組解構(gòu)
在ES6中交換變量
let a = 1,
b = 1;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
3.不定元素
let colors = ['red', 'blue', 'green'];
let [firstColor, ...restColors] = colors;
console.log(restColors.length);
4.數(shù)組復(fù)制
ES5:
var colors = ['red', 'green'];
var newColors = colors.concat();
ES6:
let [...newColors] = colors;
5.解構(gòu)參數(shù)
解構(gòu)可以用在函數(shù)參數(shù)的傳遞過程中, 更加方便
funtion setCookie(name, value, {secure, path, domain, expires} = {}) {
// 設(shè)置cookie的代碼
}
setCookie('type', 'js', {
secure: true,
expires: 6000
});