[英]Give an array a value and a list inside of it
I wish to make a list inside of an item in an array but still keep a value for that item?我希望在数组中的项目内创建一个列表,但仍保留该项目的值? Is there any way of doing that?有没有办法做到这一点?
resources: {
hyphens: 0{
rate: 0
},
ores: 0,
pitchforks: 0
I want resources.hyphens
to give back a number since I have that referenced quite a bit in my other file as such.我希望resources.hyphens
返回一个数字,因为我在其他文件中引用了很多。 But I also wish to be able to recall a value from something such as resources.hyphens.rate
that is seeded in resources.hyphens
.但我也希望能够从诸如resources.hyphens.rate
东西中召回一个值,该值是在resources.hyphens
播种的。 Any way of doing that?有什么办法吗?
You can create toString
and valueOf
methods as own properties to an object.您可以创建toString
和valueOf
方法作为对象的自己的属性。 These methods are used when ever JS needs to convert an object to a string or to a number.当 JS 需要将对象转换为字符串或数字时,就会使用这些方法。 Usually you have seen them returning "[object Object]", but for example an instance of Date
will return a date string when converted to a string.通常您已经看到它们返回“[object Object]”,但是例如Date
的实例在转换为字符串时将返回一个日期字符串。
Creating own conversion methods:创建自己的转换方法:
var resources = {
hyphens: {
rate: 5
},
ores: 0,
pitchforks: 0
};
Object.defineProperties(resources.hyphens, {
valueOf: {value: function () {return 10;}},
toString: {value: function () {return 10;}}
});
A live demo at jsFiddle . jsFiddle 的现场演示。
You can create these properties also within the object definition, but doing it this way will protect the properties, and make them also non-enumerable.您也可以在对象定义中创建这些属性,但这样做会保护这些属性,并使它们也不可枚举。
Notice, that logging resources.hyphens
directly, will show you the object structure, in the code it will behave like a number in a case a conversion is needed.请注意,直接记录resources.hyphens
将向您显示对象结构,在代码中,如果需要转换,它将表现得像一个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.