1

In a situation where I have something like this code:

var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];

Is there any way I could go through the array and initiate variables with their corresponding values? I've tried something like

for(var i=0;i<variableNames.length;i++){
    eval("var "+variableNames[i]+"="+variableValues[i]+";");
}

But I'm not getting any reults. Is eval not able to define variables, or are there other problems that exist? Any solution would be greatly appreciated.

Zach Brantmeier
  • 716
  • 3
  • 8
  • 23

2 Answers2

1

You need to assign the variables on an object. If you want to create global variables the following code should work:

for (var i=0; i<variableNames.length; i++) {
  window[variableNames[i]] = variableValues[i];
}

//test
console.log(thisMonth); //"February"    
advncd
  • 3,787
  • 1
  • 25
  • 31
0

Here you go. You missed a couple of quotes at "='" + variableValues[i] + "';");:

var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];
for(var i=0;i<variableNames.length;i++){
    eval("var "+variableNames[i]+"='"+variableValues[i]+"';");
}

With that correction however, I would warn you against using it cause it's a very wrong way of doing it.

Use Objects, as most here mention.

loxxy
  • 12,990
  • 2
  • 25
  • 56
  • Someone had to highlight the error. Maybe OP is just curious, or perhaps a reason for doing so. :) – loxxy Feb 18 '14 at 22:59