解構物件
解構是將物件的屬性提取到變數中的便捷方式。
基本語法:
let person = {
name: 'Bob',
age: 25
};
let { name, age } = person;
// Is equivalent to
let name = person.name; // 'Bob'
let age = person.age; // 25
解構和重新命名:
let person = {
name: 'Bob',
age: 25
};
let { name: firstName } = person;
// Is equivalent to
let firstName = person.name; // 'Bob'
使用預設值進行解構:
let person = {
name: 'Bob',
age: 25
};
let { phone = '123-456-789' } = person;
// Is equivalent to
let phone = person.hasOwnProperty('phone') ? person.phone : '123-456-789'; // '123-456-789'
使用預設值進行解構和重新命名
let person = {
name: 'Bob',
age: 25
};
let { phone: p = '123-456-789' } = person;
// Is equivalent to
let p = person.hasOwnProperty('phone') ? person.phone : '123-456-789'; // '123-456-789'