3 回答

TA貢獻1858條經(jīng)驗 獲得超8個贊
您應(yīng)該設(shè)置enumerable
為true
。在Object.defineProperty
其false
默認(rèn)情況下。根據(jù)MDN的說法。
枚舉
true
當(dāng)且僅當(dāng)該屬性顯示了相應(yīng)的對象的屬性的枚舉期間。
默認(rèn)為false。
不可枚舉意味著該屬性將不會在控制臺中顯示Object.keys()
或for..in
循環(huán)顯示
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
prototype
內(nèi)置類的對象的所有屬性和方法都是不可枚舉的。這就是您可以從實例中調(diào)用它們但它們在迭代時不出現(xiàn)的原因。
獲取所有屬性(包括不可枚舉)Object.getOwnPropertyNames()
。
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too

TA貢獻1859條經(jīng)驗 獲得超6個贊
默認(rèn)情況下,您使用定義的屬性defineProperty
是不可枚舉的-這意味著當(dāng)您對其進行迭代時,這些屬性將不會顯示Object.keys
(這是代碼段控制臺所做的事情)。(類似地,由于length
無法枚舉數(shù)組的屬性,因此無法顯示。)
參見MDN:
數(shù)不清的
當(dāng)且僅當(dāng)在枚舉相應(yīng)對象的屬性時顯示此屬性時,才返回true。
默認(rèn)為false。
使其可枚舉:
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
您可以在記錄的圖像中看到該屬性的原因是,Chrome的控制臺也將向您顯示不可枚舉的屬性-但不可枚舉的屬性將略顯灰色:
看看age
灰色是多少,而name
不是灰色-這表明它name
是可枚舉的,而age
不是。

TA貢獻1946條經(jīng)驗 獲得超4個贊
每當(dāng)使用對象的“ .defineProperty”方法時。您最好定義描述符的所有屬性。因為如果您不定義其他屬性描述符,則它將假定所有屬性描述符的默認(rèn)值為false。因此,您的console.log檢查所有可枚舉的true屬性,并將它們記錄下來。
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)
添加回答
舉報