变量赋值优化
//定义多个变量
let [a, b, c] = [1, 2, '3'];
console.log(a) //1
console.log(b) //2
console.log(c) //3
//如果定义变量的数量与赋值的数量不相同,超出的部分将会被忽略,缺少的变量只会被定义单不会被赋值
let [a, b, c] = [1, 2, 3, 4, 5];
console.log(a) //1
console.log(b) //2
console.log(c) //3
let [a, b, c] = [1, 2];
console.log(a) //1
console.log(b) //2
console.log(c) //undefined
//模式匹配
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 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 [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
//只要数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值
//Iterator是为各种不同的数据结构提供统一的访问机制(https://wangdoc.com/es6/iterator.html)
//具备Iterator接口的原生数据:Array、Map、Set、String、TypedArray、、函数的 arguments 对象、NodeList 对象
//解构赋值的默认值
let [ x = 1, y = 2, z = 3 ] = [ undefined, null ] //赋值为空或undefined时,使用设置的默认值
x //1
y //null
z //3
对象的解构赋值
//对象结构赋值根据属性提取,需要确保属性值与变量名相同,对于排序没有要求。
let { a, c, b } = { a: 1, b: 2, c: 3 }
console.log(a) //1
console.log(b) //2
console.log(c) //3
//自定义变量名
let { a: x } = { a: 1 }
console.log(a) //a is not defined
console.log(x) //1
//默认值
let { a = 1, b = 2, c: z = 3 } = { x: 1, y: 2 }
console.log(a) //1
console.log(b) //2
console.log(c) //3
字符串的解构赋值
//字符结构
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
//解构length
let {length : len} = 'hello';
len // 5
函数参数的解构赋值
function add([x, y]){
return x + y;
}
add([1, 2]); // 3