- 数组解构赋值
采用“匹配模式”,按照对应位置,对变量赋值
// 普通解构
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
// 解构失败
let [foo] = []; // undefined
let [bar, foo] = [1];
foo // undefined
// 部分解构(不完全解构)
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
// 解构报错,当右边没有Iterator接口(不是可遍历的结构)时
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
解构时也可以指定默认值
let [foo = true] = [];
foo // true
// 只有当一个数组成员严格等于`undefined`,默认值才会生效。
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
//如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值
function f() {
console.log('aaa');
}
let [x = f()] = [1];
// 可以引用解构赋值的其他变量,但该变量必须已经声明
let [x = 1, y = x] = []; // x=1; y=1
let [x = y, y = 1] = []; // ReferenceError: y is not defined
- 对象解构赋值
对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
// 果变量名与属性名不一致,必须写成下面这样
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
// 嵌套解构
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj; // p是模式,不是变量
p // Uncaught ReferenceError: p is not defined
x // "Hello"
y // "World"
let { p, p: [x, { y }] } = obj; // p是变量
p // ["Hello", {y: "World"}]
// 对象的解构赋值可以取到继承的属性
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
// 默认值
var {x: y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
// 数组也是特殊的对象,所以也可以这样赋值
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
注意点
(1)将一个已经声明的变量用于解构赋值,必须非常小心
// 错误的写法
// javaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。只有不将大括号写在行首,避免 JavaScript 将其解释为代码块
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正确的写法
let x;
({x} = {x: 1});
- 字符串解构赋值
// 类似数组的赋值
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
// 类似对象的赋值
let {length : len} = 'hello';
len // 5
- 数字和布尔值的解构
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
// undefined和null无法转为对象
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
- 函数参数的解构赋值
// 函数的参数会自动将参数解构
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
// 函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值
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指定默认值
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]
注意点
可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
// 全部报错
({ p: a }) = { p: 42 };
([a]) = [5];
// 报错
[({ p: a }), { x: c }] = [{}, {}];
- 用途
更多用途见 变量的解构赋值 - 用途
// 优雅的交换
let x = 1;
let y = 2;
[x, y] = [y, x];
// 遍历map结构
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}