Wanted to know how to create variables through for in javascript?

Asked

Viewed 74 times

2

because I am creating a page with javascript that has a lot of variaves that changes just like in the excerpt below

  var divClearFloat1 = document.createElement("DIV");
  var divClearFloat2 = document.createElement("DIV");
  var divClearFloat3 = document.createElement("DIV");
  var divClearFloat4 = document.createElement("DIV");
  var divClearFloat5 = document.createElement("DIV");
  var divClearFloat6 = document.createElement("DIV");
  var divClearFloat7 = document.createElement("DIV");
  • 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.

  • You can explain better what you’re gonna do with that code?

1 answer

7


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';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.