Declare a variable while the variable name is a string?

all!

I have an array containing some lines:

strs = ['a1','a2','a3']

and the object is defined:

o={}

I want to add properties to o , and the property name is a string in the strs array . Any sentence is evaluated

+3
source share
2 answers

Try to execute

for (var i = 0; i < strs.length; i++) {
  var name = strs[i];
  o[name] = i;
}

This code will create properties with data nameon the object o. After starting the cycle, you can access them in this way

var sum = o.a1 + o.a2 + o.a3;  // sum = 3

Here's a script in which there is sample code

+4
source

This can be done using the square brackets .

var strs = ['a1','a2','a3'];
var o = {};

for(i = 0; i<strs.length; i++)
{
    o[strs[i]] = "value";
}

document.write(o.a1);
+1
source

All Articles