Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare variable while the variable name is a string?

Tags:

javascript

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

like image 872
Mark Ma Avatar asked Jun 05 '26 21:06

Mark Ma


2 Answers

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/
like image 121
JaredPar Avatar answered Jun 08 '26 15:06

JaredPar


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);
like image 21
Marty Avatar answered Jun 08 '26 15:06

Marty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!