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?

4
  • 2
    console.log shows the state of cb now, and not at the time it was logged. Commented Mar 9, 2016 at 17:21
  • Possible dublicate: stackoverflow.com/questions/750486/… Commented Mar 9, 2016 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. Commented Mar 9, 2016 at 17:22
  • The log does not show the exact state of an array/object when you log it. stackoverflow.com/questions/4057440/… Commented Mar 9, 2016 at 17:37

3 Answers 3

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));
};
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.