You are pushing the same object twice. JavaScript arrays store objects by reference; both of them now refer to the same object. However, you are also using a browser that suffers from a bug that the objects written to console.log
are not displayed until after a while, and thus the value shown there is not the value of the object upon the time of console.log
but some point of time afterwards.
However, your code is still buggy.
partCp
refers here to the same object all the time; you first change that object's number
to 1
and name
to door1
, then push; and after that you change the same object's number
to 2
and name
to door2
, and push a reference to that object again; as there was only 1 object to begin with, both elements of the array are references to the same object. Now, the browser bug made you post a question, but on a working browser, if you do console.log(myDoorObj['part'])
you would see that there still are door2
s in the array.
To construct a new copy of the partCp
, see
Javascript - How to clone an object?