I'm trying to make a for
loop that depending on the objNumber
variable. It makes that many objects and names them with different variables, like so:
for (var i = 1; i <= objNumber; i++){
var myElement = new Element('div', {id: 'slot'+i, class: 'slot'});
var myObject+i = new myClass
}
I want to do this so that I can keep track of the names of all objects, and can reference them easily.
Each myObject
will create another "child" object. If I keep all objects with the same number that way I can keep track of all the objects.
Is this the best way to do it? Or is it not possible?
I'm trying to make a for
loop that depending on the objNumber
variable. It makes that many objects and names them with different variables, like so:
for (var i = 1; i <= objNumber; i++){
var myElement = new Element('div', {id: 'slot'+i, class: 'slot'});
var myObject+i = new myClass
}
I want to do this so that I can keep track of the names of all objects, and can reference them easily.
Each myObject
will create another "child" object. If I keep all objects with the same number that way I can keep track of all the objects.
Is this the best way to do it? Or is it not possible?
Share Improve this question edited Jul 20, 2011 at 14:40 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Jul 20, 2011 at 14:38 ThaiscorpionThaiscorpion 4791 gold badge8 silver badges19 bronze badges 1-
1
You probably should use an array, but for future reference, you can use variable variables in javascript like so:
var i = 'foo'; window[i+"bar"] = i; foobar == "foo"
– circusbred Commented Jul 20, 2011 at 14:57
3 Answers
Reset to default 4Just use an array:
var myObjects = [];
for (var i = 1; i <= objNumber; i++){
var myElement = new Element('div', {id: 'slot'+i, class: 'slot'});
var myObjects[i] = new myClass
}
You could use the eval statement to do this, but a better approach is to use an associative array, where the key is the variable name. Doing it this way you can easily iterate over the objects you've created, and it creates more readable code.
The best way would be to use an array:
var myArray = new Array();
for (var i = 0; i < objNumber; i++){
var myElement = new Element('div', {id: 'slot'+i, class: 'slot'});
myArray.push(new myClass());
}
Alternatively you could use the following:
var myCollectionObj = {};
for (var i = 1; i <= objNumber; i++){
var myElement = new Element('div', {id: 'slot'+i, class: 'slot'});
myCollectionObj["myObject"+i] = new myClass();
}