问题描述
我正在尝试更改数组中的字段.我使用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"});
这两种情况有何不同?
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);
和
let 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"});
您要将新值合并到一个全新的对象中(赋值{}
的第一个参数),然后用它覆盖变量.现在,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如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!