Mark Ma
Mark Ma

Reputation: 1362

declare variable while the variable name is a string?

everyone!

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

Upvotes: 3

Views: 2664

Answers (2)

Marty
Marty

Reputation: 39456

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);

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

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

Upvotes: 4

Related Questions