javascript - 为什么使用切片的克隆列表会影响原始列表

标签 javascript arrays

下面是我将数组中的对象更改为字符串的代码。无法弄清楚为什么它会影响原始数组。 slice 应该克隆数组,如果我是对的?

var cloned = $scope.selected.items.slice(0);
cloned.forEach(function (cluster) {
  cluster.status = cluster.status.name;
})
ObjToPost.MO = cloned;
console.log("consoling the cluster list", ObjToPost.MO);
console.log("consoling the original cluster list", $scope.selected.items);

经过consoling后两个数组是一样的

最佳答案

Array.prototype.slice 上引用 MDN ,

The slice() method returns a shallow copy of a portion of an array into a new array object.

这里重要的词是“浅拷贝”。它创建一个新数组,并使数组的元素指向同一个对象。

在您的情况下,即使在切片之后,原始数组和克隆数组中的每个数组元素都引用内存中的相同簇对象。

Original                        Cloned
+-----+                        +-----+
|  0  |--> Cluster Object 1 <--|  0  |
+-----+                        +-----+
|  1  |--> Cluster Object 2 <--|  1  |
+-----+                        +-----+
|  2  |--> Cluster Object 3 <--|  2  |
+-----+                        +-----+

由于所有相应的元素都引用相同的对象,因此通过一个数组更改它也会反射(reflect)在另一个数组中。

注意:如果您正在寻找进行深度复制的方法,那么您可能需要查看 this question .

关于javascript - 为什么使用切片的克隆列表会影响原始列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32907410/

相关文章:

javascript - 使用 Javascript 或 C# 从 Office 365 Outlook 加载项创建 .msg 文件

javascript - 在 JavaScript 中创建哈希数组

javascript - 将对象数组打印到 HTML 数据属性中

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

Java 平均水平及以上

javascript - 您可以在 chrome devtool 中查看以前/当前值吗?

javascript - 将 php 正则表达式转换为 javascript

php - 使用usort根据特定条件对多维数组进行排序

javascript - 在 Dialogflow 中返回 Promise 输出

c - malloc 之后的 while 循环后出现段错误