Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Thaiscorpion Avatar asked Jan 18 '26 20:01

Thaiscorpion


1 Answers

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
 }
like image 124
Sascha Goebel Avatar answered Jan 21 '26 11:01

Sascha Goebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!