1

My goal is to dynamically generate variables foo1, foo2 and foo3 and assign bar to them using the following code:

for (var i=1;i<=3;i++) {
    myapp.set({ foo+i: "bar" })
}

I tried using eval on foo by it doesn't work. Any ideas?

2
  • 1
    Why not use an array? Accessing data will be easier. Commented Aug 9, 2013 at 19:14
  • Can you post the code that you used when you tried using eval on foo? Commented Aug 9, 2013 at 19:18

3 Answers 3

4
for (var i=1;i<=3;i++) {
    var myObj = {};
    myObj['foo' + i] = 'bar';

    myapp.set(myObj);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this with square brackets. If you want the variables to be in the global scope, then use window['foo'+i].

Eg:

for (var i=1; i<=3; i++) {
    window['foo'+i] = 'bar';
    // OR, if you want them in 'myApp' scope:
    myApp['foo'+i] = 'bar';
}

3 Comments

Why put variables in the global scope? Smells like bad architecture...
It's just an example, showing a pattern you can apply to whatever scope you want. I didn't recommend OP use the global scope any more than any answer recommends you use 'foo' as a variable name.
Just saying we probably shouldn't use a global scope example. A lot of people are new to programming, and this could lead to confusion. Most new programmers understand that foo is a generic name, while a lot of people don't understand what global scope is. I guess I could have posed a better comment, but I just wanted people to think twice before copying and pasting
1

http://jsfiddle.net/TASfG/

var myApp = {};

for (var i=1; i <= 3; i++) {
    myApp['foo'+i] = "bar";
}

console.log(myApp);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.