[英]Making changes to a copied array, updates the original?
I have an array of objects: 我有一个对象数组:
let users = [{name: 'john', address: '10 king street'}, ....];
I copy this array via: 我通过以下方式复制此数组:
let usersCopy = users.slice(0);
Then if I do 那我做的话
usersCopy[0].name = jeff;
It also updated this on the original users array: 它还在原始用户数组上对此进行了更新:
console.log(usersCopy[0].name) //jeff
console.log(users[0].name) //jeff
I'm expecting to see: 我希望看到:
console.log(usersCopy[0].name) //jeff
console.log(users[0].name) //john
That's because [].slice()
does a shallow copy, meaning you get a new array, but it doesn't clone the objects underneath. 这是因为
[].slice()
了浅表复制,这意味着您将获得一个新数组,但不会克隆其下的对象。 Therefore, users[0] === usersCopy[0]
, as they are the same reference to the same object. 因此,
users[0] === usersCopy[0]
,因为它们是对同一对象的相同引用。
You will need to replace usersCopy[0]
entirely. 您将需要完全替换
usersCopy[0]
。 For example: 例如:
usersCopy[0] = {...usersCopy[0], name: 'jeff'}
Which would create a new object with everything from usersCopy[0]
shallow-copied into it. 这将创建一个新对象,
usersCopy[0]
所有内容复制到其中。
Edit: As noted below this answer is not correct 编辑:如下所述,此答案不正确
Here's an alternate way to create a separate array from the original so you can modify the clone
这是创建与原始阵列不同的数组的另一种方法,因此您可以修改
clone
const users = [{name: 'John', address: '10 king street'}]; const clone = new Array(users); clone[0].name = 'Jeff'; console.log(clone[0].name) //jeff console.log(users[0].name) //john
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.