Adding objects to the array during traversal, why is the added object the result of the last traversal?

as the title

clipboard.png

console.log(arr)

clipboard.png

console.log( obj )

clipboard.png

Jun.22,2022
In

for loop, the obj of the operation is the same object, and the obj added in arr is also the same object. After the for loop, obj.id is 4, so the obj in arr is all {id:4}


objects are reference types.


The

object is a reference type, and only the address is assigned when assigning, so the four objects in your array are all at the same address, that is, the same object

.

you can modify it like this

const obj = {id: 0}
const arr = []
for (let i = 0; i < 4; iPP) {
    obj.idPP
    arr.push(JSON.parse(JSON.stringify(obj)))
}
console.log(arr)

in addition, don't use the markdown syntax to ask questions like this, so that others can directly copy and use your code to modify it without having to type it again

.

is because of the method console.log (). If we replace it with alert (), we can get the result that meets our expectations


because arr= [. Arr,obj] is only a shallow copy of obj, in the final analysis, it is the application of obj used. If you want to make a deep copy, you can consider changing it to this:

let obj = {id:0},arr=[]
for(let i = 0;i<4;iPP){obj.id+=1;arr=[...arr,{...obj}]}
// arr [{id:1},{id:2},{id:3},{id:4}]

of course, this is only a simple first-layer deep copy, and if obj is a more complex situation, you have to consider it separately.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32742-2be10.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32742-2be10.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?