14

Possible Duplicate:
javascript - dynamic variables
Dynamic Javascript variable names

I need to create a number of objects on a page and want to name them sequentially. Is there a way to do this in JavaScript?

for (i=0;i<num;i++){
  var obj+i = new myObject("param1","param2");
  obj+i.someProperty = value;
}

This way I can dynamically create a varying number of objects (dependent on the value "num") and then set their properties appropriately.

I can do this in PHP, is there a way to do it in JavaScript?

Community
  • 1
  • 1
Terry Carnes
  • 179
  • 1
  • 1
  • 6
  • 1
    Thank you for helping! I resisted the whole idea of creating an array of objects, hadn't done that before. I asked the question thinking that it would help me to start a dialog to figure out an answer. After receiving the array answer again, I gave it a try, and it worked! Sorry for being so slow in believing that. – Terry Carnes Oct 12 '12 at 18:28

3 Answers3

14

This isn't recommended, but does what you're trying to do (if you're running in a browser and not some other js environment).

for (i = 0; i < num; i++) {
  window['obj' + i] = new myObject("param1","param2");
  window['obj' + i].someProperty = value;
}
obj0.someProperty;

This works because global variables are actually properties of the window object (if you're running in the browser). You can access properties of an object using either dot notation (myObject.prop) or bracket notation (myObject['prop']). By assigning window['obj' + i], you're creating a global variable named 'obj' + i.

The better option is to use an array or parent object to store your objects.

myObjs = {};
for (i = 0; i < num; i++) {
  myObjs['obj' + i] = new myObject("param1","param2");
  myObjs['obj' + i].someProperty = value;
}
myObjs.obj0.someProperty;

Or use an array like lots of other answers suggest.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
7

That's what arrays are for, to hold a collection of something:

var objs = [];
for (i=0;i<num;i++){
  objs[i] = new myObject("param1","param2");
  objs[i].someProperty = value;
}

Dynamic variables are almost always a bad idea.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can create, and you can set/modify properties of that object.

Modified code:

var obj = {}; //
for (i=0;i<num;i++){
  obj[i] = new myObject("param1","param2");
  obj[i].someProperty = value;
}

I recommend you to use array. as

 var obj = []; //
    for (i=0;i<num;i++){
      obj[i] = new myObject("param1","param2");
      obj[i].someProperty = value;
    }
Anoop
  • 23,044
  • 10
  • 62
  • 76