使用Array.prototype.slice()深层复制数组

[英]Deep copy an array with Array.prototype.slice()


I have known that we can use Array.prototype.slice() to perform a deep copy on array.

我知道我们可以使用Array.prototype.slice()在数组上执行深层复制。

var a = [1,2];
var b = a.slice();
b.push(3);
console.log(a);

result:

[1,2]

But in my case, I used it to perform deep copy on an array of objects. And the result was not something I would expect.

但就我而言,我用它来对一组对象进行深度复制。结果不是我所期待的。

var a = [{},{"chosen": true}];
var b = a.slice();
b[0]["propa"] = 1;
console.log(a);

result:

[{"propa":1},{"chosen":true}]

Someone shows me how to work around in this situation. Thanks.

有人告诉我如何在这种情况下解决。谢谢。

1 个解决方案

#1


2  

You can use the JSON object to serialize and deserialize the array.

您可以使用JSON对象序列化和反序列化数组。

var a = [{},{"chosen": true}];
var b = JSON.parse(JSON.stringify(a));
b[0]["propa"] = 1;
console.log(a);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/07/13/b4ed9e85d94a25a87183b9ce529fe605.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com