一.数组的解构赋值
1.ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,也就是按照相同的结构对应给值,这被称为解构(Destructuring)。
2.本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
3.解构赋值举例:
let [a, b] = [2, 3];
console.log(a, b);//输出:2 3
let [a, b, c] = [2, 3];
console.log(a, b, c);//输出:2 3 undefined
let [a, [b, c], [[d, e]]] = [0, [1, 2], [[3, 4]]];
console.log(a,b,c,d,e);//输出:0 1 2 3 4
let [, , a] = [1, 2, 3, 4, 5];
console.log(a);//输出:3
4.如果等号的右边不是数组将会报错:
let [a] = 1;
let [b] = false;
let [c] = NaN;
let [d] = undefined;
let [e] = null;
let [f] = {};
5.使用…扩展运算符拆分集合:
let a = [1, 2, 3];
console.log([...a]);//输出:Array[3]
let [a, b, ...c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c);//输出:1 2 Array[4]
let [...a, b, c] = [1, 2, 3, 4, 5];//扩展运算符只能在最后
console.log(a, b, c);//报错:Rest element must be last element in array
6.解构赋值允许指定默认值:
let [a = 0, b = 1] = [];
console.log(a, b);//输出:0 1
let [x, y = 'b'] = ['a'];
console.log(x,y);//输出:a b
二.对象的解构赋值
let { id, name } = { id: 10086, name: "张三" };
console.log(id, name);//输出:10086 "张三"
let { id, name, sex } = { id: 10086, name: "张三" };
console.log(sex);//输出:undefined
let { id: num, name: nickname } = { id: 10086, name: '小李' }
console.log(num, nickname);//输出:10086 "小李"
//以下两种写法中,第二种相当于第一种的缩写
let { a: a, b: b } = { a: 1, b: 2 };
console.log(a, b);//输出:1 2
let { a, b } = { a: 1, b: 2 };
console.log(a, b);//输出:1 2
三.数组解构和对象解构混合
let { id, name, hobby } = { id: 10086, name: '等等', hobby: [1, 2, 3] }
console.log(id,name,hobby);//输出:10086 "等等" [1, 2, 3]
let { a: [b, [c, d]] } = { a: [1, [2, 3]] };
//console.log(a);//a is not defined
console.log(b, c, d);
let { a } = { a: 1 };
console.log(a);//输出:1
let { a: b } = { a: 1 };
console.log(b);//输出:1
let { a, a: b } = { a: 1 };
console.log(a, b);//输出:1 1
let { a, a: [x, y, [z]] } = { a: [1, 2, [3]] };
console.log(a, x, y, z);//输出:Array[3] 1 2 3
四.对象解构赋值的默认值
let { a = 1, b = 2 } = { a: undefined, b: undefined };
console.log(a, b);//输出:1 2
var { x = 3 } = { x: null };
console.log(x); //输出:null,因为null与undefined不严格相等,所以是个有效的赋值,导致默认值3不会生效
let { a = 1, b = 2 } = {};
console.log(a, b);//输出:1 2
五.将已经声明的变量用于解构赋值
{
let x;
({ x } = { x: 1 });
console.log(x);//输出:1
}
六.字符串解构赋值(原理还是对象解构)
let str = new String('abcdef');
console.log(str);
let { length } = 'abcdef';
console.log(length);
let [a, b, c, d, e, f] = 'abcdef';
console.log(a, b, c, d, e, f);//输出:a b c d e f
let { a, b, c, d, e, f } = 'abcdef';
console.log(a, b, c, d, e, f);//输出:undefined undefined undefined undefined undefined undefined
//字符串解构默认转化为类数组
let { toString: s } = true;
console.log(s);
console.log(Number.prototype.toString == s);
console.log(Boolean.prototype.toString == s);
七.函数形参解构赋值
function method([a, b, ...c]) {
console.log(a, b, c);
}
method([1, 2, 3, 4, 5, 6]);//输出:1 2 Array[4]
[[1, 2], [3, 4]].map(function ([a, b], index) {
console.log(a, b, index);//输出:1 2 0 ; 3 4 1
});