Console.log displaying all array data

Asked

Viewed 3,484 times

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 browser console output 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, length is printed correctly according to the interaction, but the objects of the Array are printed in their entirety. Because this occurs?

  • In your example it seems to me x would be i.

  • True. It’s been corrected.

  • Now you left me in doubt too! I had never noticed that haha

  • Probably because arrays and objects are passed by reference, the browser must change their value when there is a change via code (only speculating)

1 answer

1

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

  1. Turn 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)));
}

  1. 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?

  • The problem is that if I implement a setTimeout and inside it I place the console.log display is fixed.

  • As you can see in the link I put in the reference some consider this behavior correct and others believe it is a console bug, because it will insert the methods calls, when you use setTimeout you delay reading the data which makes it display the result you expect, of the two ways that I implemented you do not need to add a delay in the process just displays the data in the correct way.

Browser other questions tagged

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