gpt4 book ai didi

JavaScript 向对象添加隐藏数据

转载 作者:行者123 更新时间:2023-12-01 15:30:52 27 4
gpt4 key购买 nike

假设我有一个对象,例如:

const myObj = { color: 'red', score: 8 };
我可以通过以下方式访问这些属性:
myObj.color // 'red'
和:
Object.values(myObj) // ['red', 8]
我希望能够在对象中存储额外的数据,这些数据可以访问,但 Object.values() 找不到例如:
myObj.greeting // "hello"
// or alternatively
myObj.greeting() // "hello"
Object.values(myObj // ['red', 8] greeting is not picked up by Object.values()
如有必要,最好使用现代 JavaScript 类,而不是直接使用原型(prototype)。

最佳答案

您可以使用Object.defineProperty那个集enumerable: false (默认情况下)所以它不在属性中显示/枚举:

const myObj = { color: 'red', score: 8 };
Object.defineProperty(myObj, "greeting", {
enumerable: false,
writable: true,
value: "hello"
});
console.log(myObj.greeting);
console.log(myObj);
console.log(Object.values(myObj));

根据 documentation :

This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable and not enumerable.

关于JavaScript 向对象添加隐藏数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com