解构对象
像解构数组一样,解构对象可以帮助您并使您的代码更干净、更好,但它与解构数组不同,以下是具体操作方法:
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中文网其他相关文章!