Ask a question about the memory address reference of objects in the javascript array

assign a to b

let a = [{
  m: 1
}]

let b = [...a]

b[0].m = 2

console.log(a)
console.log(b)

result:

[{m: 2}] / / a
[{m: 2}] / / b

when you change the attribute of an element in b, the m attribute in the corresponding element of an also changes

.

so how can objects in array b be redirected to a new memory address?
expected result:

[{m: 1}] / / a
[{m: 2}] / / b
Mar.25,2021

copy objects instead of reference objects. Assign, like . , is a shallow copy

.
let b = a.map(item=>{
    return Object.assign({},item)
})

let a = [{
  m: 1
}]
let b = JSON.parse(JSON.stringify(a))
b[0].m = 2
console.log(JSON.stringify(a))
console.log(JSON.stringify(b))
Menu