gpt4 book ai didi

javascript - 使用切片的数组复制不起作用

转载 作者:行者123 更新时间:2023-11-30 11:37:55 25 4
gpt4 key购买 nike

我希望在使用 distances.slice() 之后,我会得到数组的副本。但是当我更改新副本的一个元素时,它仍然会更改原始数组。为什么?

var distances = [
['-1', '10', '-1', '31'],
['10', '-1', '10', '-1'],
['-1', '-1', '-1', '10'],
['15', '6', '-1', '-1']
];
for (var i = 0; i < 4; i++) {
console.log(distances, 'distances pairstop');
var sampleDistance = distances.slice()
sampleDistance[0][2] = ['fooo']
}

最佳答案

Slice 生成数组的 副本。它在docs中这样说:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

由于 distances 是一个数组,sampleDistance 将是一个浅拷贝,这意味着它将保存对相同 3(一维)数组的引用。sampleDistance[0][2] = ['fooo'] 更改第一个一维数组,它被 sampleDistancedistances 引用.

因此你的错误。

关于javascript - 使用切片的数组复制不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com