解構物件
像解構數組一樣,解構物件可以幫助您並使您的程式碼更乾淨、更好,但它與解構數組不同,以下是具體操作方法:
let heightInCm = 4; const obj = { personName: 'spongeBob', personAge: 37, personAddress: '124 Conch Street, Bikini Bottom, Pacific Ocean', heightInCm: 10, personHobbies: [ 'Jellyfishing', 'Cooking Krabby Patties', 'Blowing Bubbles', 'Karate', ], home: { type: 'pineapple', location: 'bikini bottom', details: { rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple!", }, }, };
const { personName, personAge } = obj; console.log(personName, personAge); // spongeBob 37
*您也可以讓變數名稱與屬性名稱不同,只需將新變數名稱放在冒號後面:
const { personName: name, personAge: age } = obj; console.log(name, age); // spongeBob 37
*預設值:
const { DriversLicense = ['no'] } = obj; console.log(DriversLicense); // ['no'] // DriversLicense does not exist in obj, so the default value will be used.
* 解構物件時改變變數:
({ heightInCm } = obj); console.log(heightInCm); // 10
*嵌套物件解構:
// firstway: Extracting the Entire Nested Object const { details } = obj.home; console.log(details); // { rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple" // second way: Extracting Specific Properties const { home: { details }} = obj; console.log(details); // {rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple" // third way const {details: { rooms, uniqueFeature }} = obj.home; console.log(rooms, uniqueFeature); // 3 "it's underwater and shaped like a pineapple!"
*感謝您的閱讀,希望您明白一切,如果您有任何疑問,請隨時提問?
以上是JavaScript 物件解構的詳細內容。更多資訊請關注PHP中文網其他相關文章!