Console.log displaying all data in the array

2

When I run the javascript code below:

var dados = Array();
for (var i = 0; i < 2; ++i) {
     dados.push({index: i});
     console.log(dados);
}

The output in the browser console for the first interaction will be:

[0: {index: 0}, 1: {index: 1}, length: 1]

And for the second interaction it will be:

[0: {index: 0}, 1: {index: 1}, length: 2]

As we can see the 'length' prints correctly according to the interaction, but the Array objects are printed in their entirety. Why does this occur?

    
asked by anonymous 17.10.2018 / 13:21

1 answer

1

This is because what you see in console.log is the reference of the dados variable. There are two alternatives to resolve this problem:

  • Transform the object into a string and then return it to an object, so you can get the result you want.
  • var dados = Array();
    for (var i = 0; i < 2; ++i) {
         dados.push({index: i});
         console.log(JSON.parse(JSON.stringify(dados)));
    }
  • Clone the array before displaying it on the console
  • var dados = Array();
    for (var i = 0; i < 2; ++i) {
         dados.push({index: i});
         aux = dados.slice(); // clonando Array
         console.log(aux);
    }

    References: Is Chrome's JavaScript console lazy about evaluating arrays?

        
    17.10.2018 / 14:06