let [a, b, c] = [1, 2, 3];
// a = > 1; b => 2; c => 3;let [a, [b, c], d] = [1, [2, 3], 4];
// a => 1; b => 2; c => 3; d => undefined;// 当等号左边变量少于等号右边值时(包括变量缺省和变量个数不足), 仍可解构成功,成为不完全解构let [a, , c] = [1, 2, 3];
// a => 1; c => 3;// 多余参数的解构let [a, b, ...c] = [1, 2, 3, 4, 5];
// a => 1; b => 2; c => [3, 4, 5];// 解构不成功的情况let [a] = [];
// a => undefined;let [a, b] = [1]
// a => 1; b => undefined;// 当等号右边不是数组或类数组(即可遍历的结构) 将会报错let [a] = 1;
let [a] = false;
let [a] = NaN;
let [a] = undefined;
let [a] = null;
let [a] = {};
// TypeError: Invalid attempt to destruture non-iteable instance
对象
解构时无次序,属性名必须相同
let {a, b} = {a: 1, b: 2}
// a => 1; b => 2;let {a, b, c} = {a: 1, c: 2, d: 3}
// a => 1; b => undefined; c => 2; d => d is not definedlet {a: b} = {a: 1, b: 2}
// a => a is not defined; b => 2
字符串
相当于把字符串切割成一个数组,顺位取
let [a, b, c] = 'string';
// a => s; b => t; c => r;let [a, b, c] = '字符串也可以解构';
// a => 字; b => 符; c => 串;let [a, b, c] = '字符';
// a => 字; b => 符; c => undefined;
函数参数
let a = [1, 2];
functionlog([a, b, c]) {// 相当于 let [a, b, c] = [1, 2];
console.log(a, b, c);
// a => 1; b => 2; c => undefined;
}
log(a);
functionalert({title = 'title', content = 'content', button = 'button'}) {
console.log(title, content, button);
}
alert({title: '123'})
默认值
解构赋值也允许使用默认值
let [a = 1] = [2];
let [a = 1] = [NaN];
let [a = 1] = [true];
let [a = 1] = ['string'];
let [a = 1] = [null];
let [a = 1] = [undefined];
// 以上几种情况只哟传入的值为undefined时,默认值才会生效// null 和 NaN 并不等于 undefined// 如果默认值为表达式,那这个表达式是惰性求职的let [a = b()] = [1];
functionb() {// 无输出结果
console.log('验证是否为惰性求值');
}
let b = 1;
let [a = ++b] = ['string'];
// a => string, b => 2let [a = ++b] = [undefined];
// a => 2, b => 2
用途
// 交换宾变量的值let [x, y] = [1, 2];
// x => 1; y => 2;
[y, x] = [x, y];
// x => 2; y => 1;// 从数组或者json中提取值functionparams() {return [1, 2, 3];
}
let [a, b, c] = params();
let obj = {
a: 1,
b: 2,
c: 3
}
let {a, b, c} = obj;
// 函数参数的默认值functionalert({title = 'title', content = 'content', button = 'button'}) {
console.log(title, content, button);
}
alert({title: '123'});
// 导入模块的指定值
import {A, B} from './const'