Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create dynamic object names in JavaScript? [duplicate]

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?

like image 801
Terry Carnes Avatar asked Oct 10 '12 18:10

Terry Carnes


People also ask

Can we add dynamically named properties to JavaScript object?

So the best way of adding dynamically created property is the [bracket] method. Show activity on this post. Example: ReadValue("object.

Can I create dynamic variable in JavaScript?

The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.

Are JavaScript objects dynamic?

A JavaScript object is syntactically defined as a function, which is itself a first instance and that is cloned to create more instances. In addition, this structure is dynamic, methods (in fact inner functions) and attributes may be added during the execution of the script.


2 Answers

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.

like image 186
Trevor Dixon Avatar answered Oct 03 '22 09:10

Trevor Dixon


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.

like image 32
Felix Kling Avatar answered Oct 03 '22 09:10

Felix Kling