JavaScript – 解构赋值 Destructuring Assignment
作者:互联网
Array Destructuring Assignment
old school
const items = [1, 2, 3]; const item1 = items[0]; const item2 = items[1]; const item3 = items[2];
一个一个从 array 拿出来, 再一个一个 assign 给每一个变量.
modern
const [item1, item2, item3] = [1, 2, 3];
一行里面做了 declare, assign, read from array. 3 个动作一气呵成.
get someone
const [, , value3] = [1, 2, 3];
with default value
const [v1] = []; // v1 = undefined const [v1 = 'default value'] = []; // v1 = 'default value' const [v1 = 'default value'] = ['value']; // v1 = 'value'
Object Destructuring Assignment
它和 Array 的用法差不多.
const person = { name: 'Derrick', age: 11 }; const { name, age } = person;
with alias 别名
const person = { name: 'Derrick', age: 11 }; const { name: newName, age: newAge } = person; console.log(newName); console.log(newAge);
name: newName 中间使用了分号
with default value
const { name = 'Derrick', age } = {}; // name = 'Derrick' // age = undefined
标签:const,name,default,Assignment,age,JavaScript,value,解构,v1 来源: https://www.cnblogs.com/keatkeat/p/16229773.html