declare variable while the variable name is a string?
ever开发者_如何学Goyone!
I have an array containing some strings:
strs = ['a1','a2','a3']
and an object is defined:
o={}
I wanna add properties to o while the property name is the string in array strs Any suggestion is appreciated
Try the following
for (var i = 0; i < strs.length; i++) {
var name = strs[i];
o[name] = i;
}
This code will create the properties with the given name
on the object o
. After the loop runs you will be able to access them like so
var sum = o.a1 + o.a2 + o.a3; // sum = 3
Here's a fiddle which has some sample code
- http://jsfiddle.net/eYJrJ/
This can be done using Square Bracket Notation.
var strs = ['a1','a2','a3'];
var o = {};
for(i = 0; i<strs.length; i++)
{
o[strs[i]] = "value";
}
document.write(o.a1);
精彩评论