简体   繁体   中英

Assigning one array to another javascript

So array in javascript are assigned by references so for example

let a = [1,2,3];

let b = a;

a = [];

console.log(b);

Shouldn't it print empty array as a is assigned to empty array and b and a are point to same.

I know that such behavior might seem weird. However, as other writers already mentioned, what happens is that by writing 'a = []' you actually assigned 'a' a new reference (ie you are not manipulating the 'old' array any more), and 'b' will hold an old reference to a memory location where 'old' array was initially assigned and break a relationship with 'a'. Hence, there will now exist 2 references instead of an initial 1.

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