Can I create dynamic object names in JavaScript?

Terry Carnes picture Terry Carnes · Oct 10, 2012 · Viewed 30k times · Source

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?

Answer

Trevor Dixon picture Trevor Dixon · Oct 10, 2012

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.