目录
解构:更易获取数据
拆对象的数据
let node = {
type: "Identifier",
name: "foo"
};
let { type, name } = node;
// assign different values using destructuring
// 不可省略(),否则会将左侧的{}视为block,语法错误
({ type, name } = node);
var {type, name, value} = node // value would be 'undefined'
var {type, name, value = true} = node // value would be true
function outputInfo(value) {
console.log(value === node);
}
outputInfo({ type, name } = node); // true
- 注意,用let 或var 拆对象的时候,右边必须有值赋给它,否则语法错误
- 如果是const,不管是不是在拆数据,右边都必须赋值
- 表达式的值等于右侧的值,可以把表达式放在函数的参数中使用
- 右侧的值不能为 null 或者 undefined
- 可以给左侧的变量赋一个默认值,如果没有默认值,而右侧又没有在对象里找到对应的Key,则变量为undefined
给不同名的本地变量赋值
let {type: localType, name:localName} = node; // localType :"Identifier", localName: "bar"
let {type: localType, wawa: localName = "bar" } = node ; // localName : "bar"
解析嵌套对象的数据
- 注意是最里层的被解析出来,外层的loc只是起到定位的作用。
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
}
};
let { loc: { start }} = node;
// start = {
line:1,
column:1
}
拆数组的数据
let colors = [ "red", "green", "blue" ];
let [ , , thirdColor ] = colors;
最有用的用处是swap。交换两个变量的值而不用第三个变量。
let a = 1, b = 2
[a,b] = [b,a]
console.log(a,b) 2,1
嵌套数组也是一样的
let colors = [ "red", [ "green", "lightgreen" ], "blue" ];
let [ firstColor, [ secondColor ] ] = colors;
console.log(secondColor); // "green"
rest items
用 …arr 来将数组中的剩余所有项赋给arr。
let [fristColor, ...restColors] = colors
//restColors 就是colors[0]之后的所有值组成的一个数组,值就等于colors.slice(1)
let colors = [ "red", "green", "blue" ];
let [ ...clonedColors ] = colors;
// 另一个作用,得到colors的复制项
混合解构数据
- 就是把两者结合起来,没什么特别的。
- 注意左侧的只是寻位符,与右侧的属性位置对应。
- 不需要整个解构,需要某个数据时特别好用(比如解析json)
- 最常用:函数object形参结构,顾名思义的函数参数
function setCookie(name, value, { secure, path, domain, expires }) {
console.log(secure,path,domain,expires)
// true undefined undefined 60000
}
setCookie("type", "js", {
secure: true,
expires: 60000
});
// 注意 setCookie() 的第三个实参一定要有。。而且不能是 null/undefined , 或者要给默认值
function setCookie(name, value, { secure, path, domain, expires } = {}) {
// ...
}
//也可以先一个一个地给单独的变量赋值,再给总的一个值
function setCookie(name, value,
{
secure = false,
path = "/",
domain = "example.com",
expires = new Date(Date.now() + 360000000)
} = {}
) {
// ...
}
summary
- using object literal and array literal syntax
- specify default values to prevent the right side be null or undefined
- 更像用等号右边的值来override左侧的变量
- make “options” more transparent when used as function parameters
本文详细介绍了ES6中的解构赋值,包括拆解对象和数组的数据,如何给变量设置默认值,解析嵌套结构,以及rest items的使用。解构赋值使得从对象和数组中提取数据更加方便,尤其是在处理函数参数和避免临时变量时。

被折叠的 条评论
为什么被折叠?



