Rumah >hujung hadapan web >tutorial js >Pemusnahan Objek JavaScript
Memusnahkan Objek
Seperti memusnahkan tatasusunan, memusnahkan objek membantu anda dan menjadikan kod anda lebih bersih dan lebih baik, tetapi ia berbeza daripada memusnahkan tatasusunan, berikut ialah cara untuk melakukannya:
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
*Anda juga boleh membuat nama pembolehubah berbeza daripada nama sifat, tepat pada nama pembolehubah baharu selepas titik bertindih:
const { personName: name, personAge: age } = obj; console.log(name, age); // spongeBob 37
*Nilai Lalai:
const { DriversLicense = ['no'] } = obj; console.log(DriversLicense); // ['no'] // DriversLicense does not exist in obj, so the default value will be used.
* Mengubah Pembolehubah semasa Memusnahkan Objek:
({ heightInCm } = obj); console.log(heightInCm); // 10
*Pemusnahan objek bersarang:
// 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!"
*Terima kasih kerana membaca, harap anda memahami segala-galanya, jika anda mempunyai sebarang pertanyaan boleh bertanya ?
Atas ialah kandungan terperinci Pemusnahan Objek JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!