es6允许从数组和对象中提取值,再对变量进行赋值,这被称为解构。
数组赋值和对象赋值:
let [a, b, c] = [1, 2, 3];
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
let { log, sin, cos } = Math;
// 例二
const { log } = console;
log('hello') // hello
let{foo,bar}={ foo: 'aaa', bar: 'bbb' };//等价于下面:
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
foo是模式,baz是变量,真正被赋值的是变量baz,而不是模式foo。
解构赋值的默认值
对象的解构赋值的默认值:
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x: y = 3} = {};
y // 3
var {x: y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
默认值生效的条件是,对象的属性值严格等于undefined。
数组的解构赋值的默认值:
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
函数的解构赋值的默认值:
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]
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]
这俩的区别是:第一个函数:{x = 0, y = 0} = {}是为变量x和y指定默认值;
第二个:{x, y} = { x: 0, y: 0 } 为函数move的参数指定默认值
function move({x = 0, y = 0} ) {
return [x, y];
}
move(); // [0, 0]
VM5715:1 Uncaught TypeError: Cannot destructure property `x` of 'undefined' or 'null'.
at move (<anonymous>:1:15)
at <anonymous>:1:1
move({});
(2) [0, 0]
move({x: 3});
(2) [3, 0]
move({x: 3, y: 8});
(2) [3, 8]
变量解构的用途
1)交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
2)从函数返回多个值,从中取值;
3)提取 JSON 数据
4)参数是一组无次序的值,函数参数的定义
5)函数参数的默认值
6)遍历 Map 结构
7)输入模块的指定方法