For this kind of thing, there are arrays, which are an indexed collection of data.
Instead of doing variavel1
, variavel2
, you use a single variable, and an index of which data stored within it refers to (variavel[1]
).
To initialize a array already with data:
var lista = [
1,
2,
3
];
var nomes = [
'Zé',
'Maria',
'Chico'
];
As in your case you will use a loop, can start with an empty array, and add a new data in a array without deleting or overwriting the previous ones, JS has the method push
:
lista = [];
lista.push(30);
lista.push(12);
lista.push(53);
// lista passou a ser [30, 12, 53]
See a simple example of creating 10 independent information using array:
var lista = []; // aqui criamos um array vazio de nome "lista"
var i;
for(i = 0; i < 10; i++ ) {
// troque o i * i pelo que quiser armazenar
// por exemplo, push( document.createElement( ... ) );
lista.push( i * i );
}
document.body.innerHTML += "O valor de lista[5] é " + lista[5];
In your case, just do this on the line of push
lista.push( document.createElement("DIV") );
And to use any item, just put the index between the brackets:
lista[5].innerText = 'Cinco';
I can’t tell you if this is the best javascript approach, but for a notion of algorithms, it would be better if you made an array or a list and filled in its positions.
– Filipe Santiago
You can explain better what you’re gonna do with that code?
– Sergio