为什么用切片的效果原来的名单列表克隆 [英] Why does Cloning list using slice effects the original list
问题描述
下面是我的code改变数组内的对象转换为字符串。想不通为什么它会影响原始数组。片应该克隆阵列,如果我是正确的?
Below is my code to change an object inside an array into a string. Can't figure out why it effects the original array. slice is supposed to clone array, if I am right?
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);
安慰之后,该阵列是相同的。
After consoling both the arrays are same
推荐答案
的片()
方法返回一个数组的一部分的浅拷贝到一个新的数组对象。
The
slice()
method returns a shallow copy of a portion of an array into a new array object.
这里最重要的词是浅拷贝。它创建了一个新的磁盘阵列,使阵列点的元素相同的对象。
The important words here are "shallow copy". It creates a new Array and makes the elements of the array point to the same object.
在你的情况下,即使切片之后,在各自的原始和克隆数组的数组元素的引用在同一个集群对象在内存中。
In your case, even after slicing, each of the array elements in both the original and cloned arrays refer the same cluster objects in memory.
Original Cloned
+-----+ +-----+
| 0 |--> Cluster Object 1 <--| 0 |
+-----+ +-----+
| 1 |--> Cluster Object 2 <--| 1 |
+-----+ +-----+
| 2 |--> Cluster Object 3 <--| 2 |
+-----+ +-----+
由于所有的相应的元件指的是相同的目的,通过一个阵列改变它会被反映在其它以及
Since all the corresponding elements are referring to the same objects, changing it through one array will be reflected in the other as well.
注意:如果您正在寻找一个方式做深度复制,那么你可能要检查这个问题。
Note: If you are looking for a way to do deep copy, then you might want to check this question.
这篇关于为什么用切片的效果原来的名单列表克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!