Splice doesn't copy array of objects [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

This question already has an answer here:

In this plunk I have an example of an array of objects a that I copy with slice() to b. I alter one of the objects in a but it changes also b. Isn't slice supposed to copy the array, including its contents? I need a and b to have different pointers.

Javascript

var a = [{x1:1, x2:2}, {x1:3, x2:4}];  var b = a.slice();   a[1].x1 = 5;   console.log(b[1]); 

this prints:

x1: 5  x2: 4 

回答1:

From MDN:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array does not affect the other array.

Performing a deep copy on objects in the array is difficult, but this answer suggests a way to do it, as long as your array only contains JSON-serializable content:

var clonedArray = JSON.parse(JSON.stringify(originalArray));



回答2:

You can try to do Deep copy with jQuery:

var b = $.extend(true,{},a); 

This does a proper deep copy of all your variables.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!