Zach Brantmeier
Zach Brantmeier

Reputation: 746

Defining variables dynamically in Javascript

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.

Upvotes: 1

Views: 82

Answers (2)

loxxy
loxxy

Reputation: 13151

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.

Upvotes: 0

advncd
advncd

Reputation: 4025

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"    

Upvotes: 1

Related Questions