JavaScript – 解構賦值 Destructuring Assignment
阿新 • • 發佈:2022-05-06
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