1

I'm confuse the way how Google Chrome developer tool console is displaying if the (A) is the actual object created in the loop, why are the (B) contains 3 objects?

Does it means (A) will contain 3 objects?

Demo: https://jsfiddle.net/LygmkgLm/

var test={}
for(var i=0;i<3;i++){
  test[i]={}
  test[i].y="111"
console.log("test",test)
}

enter image description here

4

2 Answers 2

4

You're misinterpreting the console output. It correctly and and as expected shows the increasing contents of the object within the loop, hence the 1, 2 and 3 members in the output. At the end however the variable 'test' is the fully filled object, and when you expand the first line it shows the contents at the time of expansion. Being the fully filled object with 3 children.

Your confusion arises from the fact that the logging does not store the state of the object at logging time.

Sign up to request clarification or add additional context in comments.

2 Comments

You explained it simply, though tried hard to put my words simple in answer. :) But I was trying to explain same point.
Yeah, your explanation makes it easier to digest. It felt like a realtime logging but is simply more like a simulator, that's really efficient.
1

Chrome console shows the final object in console. It shows whatever the values have gone through the object. So in console first it will show you

test Object {0: Object}

But when you extend, it will have three object which has passed through it.

test Object {0: Object}0: Object1: Object2: Object__proto__: Object

One thing to note that, at first iteration of the loop, you may see three object in console but only one object i.e.

test Object {0: Object}

is actually accessible. If you want to check actual state of object in each iteration, you have to clone it like below

var newObject = jQuery.extend(true, {}, test);

Here is the fiddle which will give you an idea of my points https://jsfiddle.net/qtdurtzc/

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.