解构赋值

1. 忽略值

1
2
3

const [apple, , banana] = ['apple', 'pear', 'banana'];
console.log(apple, banana); // apple banana

2. 分配剩余值

1
2
3
4
5
6

const [one, two, ...remainingNum] = [1, 2, 3, 4, 5];
console.log(remainingNum); // [3, 4, 5]

const { apple, pear, ...remainFruits } = { apple:'apple', pear:'pear', banana:'banana', cherry:'cherry' };
console.log(remainFruits); // { banana:'banana', cherry:'cherry' }

3. 组合的数组和对象 - 解构

1
2
3

const [, , { name }] = [{id:1, name:'apple'}, {id:2, name:'pear'}, {id:3, name:'banana'}];
console.log(name); // banana

4. 交换数组中的变量

1
2
3

const fruits = ['apple', 'pear', 'banana'];
[fruits[2], fruits[1]] = [fruits[1], fruits[2]];

5. 重命名变量

1
2
3

const { apple, pear, bUNana: banana } = { apple:'apple', pear:'pear', bUNana:'banana' };
console.log(banana); // banana

6. 设置默认值

1
2
3
4
5
6

const { banana = 'banana', apple } = { banana:undefined, apple:'apple' };
console.log(banana); // banana

const [one, two, three = 3] = [1, 2, undefined];
console.log(three); // 3

7. 嵌套结构

1
2
3
4
5
6

const { banana, fruitList: [{ apple: nestedApple }] } = {
  banana: 'banana',
  fruitList: [{ apple: 'apple' }, { pear: 'pear' }]
};
console.log(nestedApple); // apple

8. 动态对象键

1
2
3
4
5

const fruits = {banana:'banana', cherry: 'cherry'};
const fruitKey = 'banana';
const {[fruitKey]:fruitOfChoice} = fruits;
console.log(fruitOfChoice); // banana

9. 解构函数参数

1
2
3
4

const getCherry = ({banana, cherry}) => console.log(cherry);
const fruits = {banana: 'banana', cherry: 'cherry'};
getCherry(fruits); // cherry