1.解构赋值
1.1 数组的解构赋值
let a = 1;
let b = 2;
let c = 3;
改写成:
let [a, b, c] = [1, 2, 3];
再如获取数组的前两项:
const arr = [1, 2, 3, 4];
// 常规
const first = arr[0];
const second = arr[1];
// 解构赋值
const [first, second] = arr;
// 忽略某个值
let [x, , y] = [1, 2, 3];
x // 1
y // 3
1.2 对象的解构赋值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
当一个方法需要返回多值时
function processInput(input) {
return { left, right, top, bottom };
}
const { left, right } = processInput(input);
2.扩展运算符
解构赋值与扩展运算符:
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"