1
var cb = [];
for (var i = 0; i < 10; i++) {
    cb.push({
        'test': 'value'
    });
    console.log(cb);
};

I'm expecting to get: [{test: value}, {test: value}, ... , {test: value}]

What I end up getting is the final result at every log statement:

[Object]

[Object, Object]

[Object, Object, Object]

[Object, Object, Object, Object]

[Object, Object, Object, Object, Object]

[Object, Object, Object, Object, Object]

[Object, Object, Object, Object, Object, Object]

..........

When I expand any of those arrays they all have the same result. For example, the first array contains:

[{test: value}, {test: value}, ... , {test: value}] 

which is the final value, shouldn't it just have 1 object? The final result is what I expect, but I'm just confused about why after the first push the array has 10 elements. Can someone please explain what's going on?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Milan Dimic
  • 23
  • 1
  • 2
  • 6
  • 2
    `console.log` shows the state of `cb` *now*, and not at the time it was logged. – Siguza Mar 09 '16 at 17:21
  • Possible dublicate: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Bjørn Sørensen Mar 09 '16 at 17:21
  • 2
    Try doing `console.log(JSON.stringify(cb))` and you'll see what @Siguza is saying. Or even `console.log(cb.length)` will show you that the length is increasing correctly. – Mike Cluck Mar 09 '16 at 17:22
  • The log does not show the exact state of an array/object when you log it. http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – epascarello Mar 09 '16 at 17:37

3 Answers3

3

You need to serialize yor output. Try:

var cb = [];
for (var i = 0; i < 10; i++) {
    cb.push({
        'test': 'value'
    });
    console.log(JSON.stringify(cb));
};
AlanShearer
  • 141
  • 3
0

You are logging the array object, not any aspects of the object. The output is correct and so is the array. You just need to be more specific. If you set a breakpoint into the code where your console.log line is, you'll see that the array is being populated correctly.

And, if you don't want to see the object's state as it's being built, just move the log outside of the loop.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Doing cb[test]="value" (or maybe cb[myObject]="value"? I'm not sure what you want) would have returned what you expected : an array whose only key test (or myObject) contains the defined value.

When using push instead, you use the array not as an associative array (key = value) but rather as an indexed array (index = value), and push's contract is to add to the end of the array, using the next available index.
So now cb[0] is {test: "value"} and so are the others cb[1] to cb[9].

Aaron
  • 24,009
  • 2
  • 33
  • 57