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?

1
  • 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. Commented Oct 12, 2012 at 18:28

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i agree, the above code works. But don't do it!
I think it's important to point out that these variables will be global then.
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.

Comments

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;
    }

1 Comment

I know this is old but this doesnt create a dynamic object name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.