拼接不复制对象数组 [英] Splice doesn't copy array of objects

查看:63
本文介绍了拼接不复制对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此插件中我有一个对象数组示例我使用 slice()复制到 b 的a .我更改了 a 中的一个对象,但它也更改了 b .难道 slice 应该复制数组,包括其内容吗?我需要 a b 具有不同的指针.

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

Javascript

var a = [{x1:1, x2:2}, {x1:3, x2:4}];

var b = a.slice();


a[1].x1 = 5;


console.log(b[1]);

此打印:

x1: 5 
x2: 4

推荐答案

来自MDN:

对于对象引用(不是实际对象),切片复制对象引用到新数组中.原始数组和新数组都引用到同一个对象.如果引用的对象发生更改,则更改为新阵列和原始阵列均可见.

对于字符串,数字和布尔值(不是String,Number和Boolean对象),切片复制值放入新数组中.更改字符串,数字或布尔值一个数组不会影响另一个数组.

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.

很难对数组中的对象执行深度复制,但是 此答案 建议方法,只要您的数组仅包含JSON可序列化的内容即可:

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));

这篇关于拼接不复制对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆