Object.assign 是如何工作的? [英] How does Object.assign work anyway?

查看:39
本文介绍了Object.assign 是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改数组中的字段.我使用 find 函数来获取对象,然后使用 Object.assign 覆盖数组中的值.

I'm trying to change the field in the array. I used find function to get the object and then I used Object.assign to overwrite the value from the array.

然而,在一种情况下它有效:

However, in one case it works:

Object.assign(item2, {id:3, name: "Do"});

在另一种情况下,它不会:

and in the other case, it doesn't:

item = Object.assign({}, {id:3, name: "Do"});

这两种情况有什么不同?

What's different for those two cases?

let arr = [{id:1, name:"John"}, {id:2, name: "Doe"}];
let item = arr.find((x)=> x.id === 2);

//the array is not changed!
item = Object.assign({}, {id:3, name: "Do"});
console.log(arr);

let item2 = arr.find((x)=> x.id === 2);
//the array is changed!
Object.assign(item2,  {id:3, name: "Do"});
console.log(arr);

来源:http://jsbin.com/mametudemo/1/edit?html、js、控制台

推荐答案

你有

let item = arr.find((x)=> x.id === 2);

让 item2 = arr.find((x)=> x.id === 2);

在这两种情况下,变量都是对同一对象的引用",该对象包含在数组 arr 中.这意味着,如果您更改其中任何一个,这些更改将反映到其他(甚至在数组中)中,因为它们实际上引用了完全相同的对象.

In both cases the variables are a "reference" to the same object, the object contained inside the array arr. That means that if you change any of them, the changes are reflected into the others (even in the array) because they actually refer to exact same object.

现在,您以两种不同的方式修改这两个变量.在这种情况下

Now, you modify the two variables in two different ways. In this case

Object.assign(item2, {id:3, name: "Do"});

您正在将新值合并到 item2 中,因为它是一个引用,所以更改会反映到数组中.

You're merging the new values into item2, and because it is a reference, the changes are reflected into the array.

第二种情况:

item = Object.assign({}, {id:3, name: "Do"});

您正在一个全新的对象中合并新值(assign {} 的第一个参数),然后您覆盖变量 item 与它.现在 item 不再是对数组内对象的引用.它是一个新对象,因此不会触及数组内的对象.

You're merging the new values in a brand new object (the first parameter of assign {}) and then you overwrite the variable item with it. Now item is no longer a reference to the object inside the array. It is a new object, and consequently the object inside the array is not touched.

这篇关于Object.assign 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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