简体   繁体   中英

Best way to define javascript associative array where keys are variables?

To be more precise, lets say I need to define 50 different keys like:

myVar[myObj.something] = "something";
myVar[myObj.somethingElse] = "something else";
myVar[myObj.anotherThing] = "another thing";
...
myVar[myObj.lastThing] = "last thing";

So basically, I need to store bunch of strings in an array/object, with keys that are defined in another object. Is there better solution than one above? Something like:

var myVar = {
   myObj.something : "something",
   ...
}

I don't see it different.

If the values are also in another object, then you could do something like for(var key in myObj) and then easily do myVar[ myObj[key] ] = ???; .

But the question is: what will you replace ??? with. So, if it's just the static strings associated to the different key, then your example is good enough I think, and you won't get anything notably much better than it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM