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.

asked Feb 18, 2014 at 22:47
8
  • Why would you want to? Use an object. Commented Feb 18, 2014 at 22:49
  • possible duplicate of stackoverflow.com/questions/12167800/… Commented Feb 18, 2014 at 22:49
  • As stated above; do obj[variableNames[i]] = variableValues[i]; Commented Feb 18, 2014 at 22:50
  • some explanation: stackoverflow.com/questions/5117127/… Commented Feb 18, 2014 at 22:50
  • @Johan, correct, and that obj could be window Commented Feb 18, 2014 at 22:51

2 Answers 2

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" 
answered Feb 18, 2014 at 22:53
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Feb 18, 2014 at 22:55

1 Comment

Someone had to highlight the error. Maybe OP is just curious, or perhaps a reason for doing so. :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.