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?

Eric
  • 95,302
  • 53
  • 242
  • 374
MarkL
  • 8,770
  • 7
  • 26
  • 27

3 Answers3

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

    myapp.set(myObj);
}
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
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';
}
tuff
  • 4,895
  • 6
  • 26
  • 43
  • Why put variables in the global scope? Smells like bad architecture... – RestingRobot Aug 09 '13 at 19:26
  • 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. – tuff Aug 09 '13 at 19:31
  • 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 – RestingRobot Aug 09 '13 at 19:42
1

http://jsfiddle.net/TASfG/

var myApp = {};

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

console.log(myApp);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132