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. But I also wish to be able to recall a value from something such as resources.hyphens.rate
that is seeded in resources.hyphens
. Any way of doing that?
You can create toString
and valueOf
methods as own properties to an object. These methods are used when ever JS needs to convert an object to a string or to a number. 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.
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;}}
});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.