Thaiscorpion
Thaiscorpion

Reputation: 479

How to increasingly change variable name inside a loop

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?

Upvotes: 3

Views: 8342

Answers (3)

Colin
Colin

Reputation: 2021

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();

 }

Upvotes: 0

Chris Eberle
Chris Eberle

Reputation: 48775

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.

Upvotes: 0

Sascha Goebel
Sascha Goebel

Reputation: 323

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

Upvotes: 4

Related Questions