一、解構的定義
JavaScript 對象是由鍵值對組成的無序集合,在許多場景下需要從中獲取某些值。對象解構是從對象中提取出其中一些值,使得它們可以被保存在變量中。
對象解構是在 ES6 中引入的一項新功能,它提供了一種簡潔易懂的語法來從對象中獲取值。
// 定義一個對象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 從對象中獲取值
const { firstName, lastName } = person;
console.log(firstName); // 輸出:John
console.log(lastName); // 輸出:Doe
二、基本使用
在使用對象解構時,需要定義一個新的變量,再通過對象解構的語法來從原對象中提取出我們需要的值。
對象解構使用花括號{}表示,用於指定從哪個對象中提取哪些屬性,然後將其存儲到一個變量中。
// 定義一個對象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 從對象中獲取值
const { firstName, lastName, age, city } = person;
console.log(firstName); // 輸出:John
console.log(lastName); // 輸出:Doe
console.log(age); // 輸出:30
console.log(city); // 輸出:New York
三、重命名
有時候,從對象中提取出來的屬性名並不符合我們的變量命名規範,此時我們可以使用冒號:對新變量進行命名。
// 定義一個對象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 從對象中獲取值,並進行重命名
const { firstName: fName, lastName: lName } = person;
console.log(fName); // 輸出:John
console.log(lName); // 輸出:Doe
四、默認值
從對象中提取值時,如果屬性值不存在,則會賦予變量 undefined 值,但我們可以給對象解構中的變量設置默認值。
// 定義一個對象
const person = {
firstName: 'John',
lastName: 'Doe'
};
// 從對象中獲取值,並設置默認值
const { firstName = 'Jane', lastName = 'Doe', age = 30 } = person;
console.log(firstName); // 輸出:John
console.log(lastName); // 輸出:Doe
console.log(age); // 輸出:30
五、函數參數
對象解構同樣可以用於函數參數傳遞中,從而簡化代碼。
// 定義一個對象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 定義一個函數,使用對象解構作為參數
function displayPerson({ firstName, lastName, age, city }) {
console.log(`Name: ${firstName} ${lastName}`);
console.log(`Age: ${age}`);
console.log(`City: ${city}`);
}
// 調用函數
displayPerson(person);
六、嵌套對象
如果對象中的屬性也是一個對象,我們同樣可以使用對象解構來方便的獲取內部對象的屬性。
// 定義一個對象
const person = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
zipcode: '10001'
},
hobbies: ['music', 'movies', 'sports']
};
// 從嵌套對象中獲取值
const { name, address: { street, city, zipcode }, hobbies } = person;
console.log(name); // 輸出:John Doe
console.log(street); // 輸出:123 Main St
console.log(city); // 輸出:New York
console.log(zipcode); // 輸出:10001
console.log(hobbies); // 輸出:['music', 'movies', 'sports']
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/246836.html