我想以不同的分配复制数组的数组。
我知道我可以通过以下方式复制数组:
a = [[1, 2], [3, 4]]
b = a.slice() // this makes sure that a and b are allocated differently in memory
现在,如果我在b内进行更改,那么当然
b[0] = 'abc'
console.log(a, b) // expect a = [[1,2], [3,4]] and b = ['abc', [3,4]]
但是当我执行以下操作时,a也将发生变化...!
b[0][0] = 'abc'
console.log(a, b) // now it gives a = [['abc', 2], [3, 4]] and b = [['abc', 2], [3, 4]]
为什么会发生这种情况,如何避免突变a?
非常感谢!
最佳答案
如果您知道只复制2D数组,则可以使用以下函数,并避免使用JSON:
function copy2D(array){
result = []
array.forEach((subArray) => {
result.push(subArray.slice())
})
return result
}