简体   繁体   中英

JavaScript pushing an object in an array is what - by reference or value?

When I create an object and push it to an array, is it stored by reference or value?

I see the following happening:

var abc = { a: 10, b: 20};
var def = [];
def.push(abc);

abc.a = 100;

def[0].a; // outputs 100!

// if I do this
abc = { a: 10000, b: 20000 };

def[0].a; // still 100, no change this time

Image from console:

控制台中的图像

If I use the = sign to assign an object to abc , the reference pointed by abc in the array def should also change, isn't it?. What do we call above, by value or by reference?

I have understood it like abc is a reference pointing to a value. As long as we don't use = sign, it will keep pointing to that. Please guide.

Objects are ALWAYS passed by reference.

When you write abc = { a: 10000, b: 20000 } , what you are overwriting is the variable abc , which was pointing to the old object, but is now pointing to the new one.

Let's have a look at what is happening:

var abc = { a: 10, b: 20};

A new object is created in memory and assigned to the variable abc .

var def = [];

A new array is created in memory and assigned to the variable def .

def.push(abc);

Inside the array there is now a pointer to the formerly created object.

 abc.a = 100;

 def[0].a; // outputs 100!

Obviously right. We are modifying the object, which is also referenced by the array.

 abc = { a: 10000, b: 20000 };

Again a new object is created and a reference to it is stored in abc . Now we have two objects (and an array) in memory.

 def[0].a; // still 100, no change this time

Of course, this is still 100 . The array pointer still references the first created object and not the second one.

as you said create an object so then you are dealing with references.

in your second statement abc = { a: 10000, b: 20000 }; what you actually did is just make variable abc pints into new object make it reference to something else than the old abc

The reason of the problem is when you push the object to array, it clones it self. I mean in the array there is a clone of the object. Therefore if you change the properties of the object, there is nothing will change. Because you have had 2 object already. If you want to overwrite it you have use def[0] = abc after definition of abc with new values. Except for the fact that you can not change the values without asigning it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM