I wanted to know how to create variables through for in javascript?

2

I am creating a page with javascript that has a lot of variations that only changes as in the section 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");
    
asked by anonymous 22.12.2016 / 00:21

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 variable only, and an index of which of the data stored within it refers ( 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 , you can start with an empty array, and append new data to an array without erasing or overwriting the JS has method push :

lista = [];
lista.push(30);
lista.push(12);
lista.push(53);

// lista passou a ser [30, 12, 53]

See a very 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 in the line of push

lista.push( document.createElement("DIV") ); 

And to use any item, simply enter the index between brackets:

lista[5].innerText = 'Cinco';
    
22.12.2016 / 01:06