解构赋值
2019-01-13 本文已影响0人
Jason_Shu
一. 数组的解构赋值
let [a, b, c] = [1, 2, 3];
a // 1
b // 2
c // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // 'a'
y // undefined
z // []
存在不完整解构赋值。
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
二. 对象的解构赋值
let { foo, bar } = { foo: "aaa", bar: "bbb" };
// 等价于
let { foo: foo, bar: bar} = { foo: "aaa", bar: "bbb" };
foo // 'aaa'
bar // 'bbb'
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let { loc, loc: { start }, loc: { start: { line }}} = node;
line // 1
loc // Object {start: Object}
start // Object {line: 1, column: 5}
三. 字符串的解构赋值
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
四. 函数的解构赋值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。
注意,下面的写法会得到不一样的结果。
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
上面代码是为函数move的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。