我希望在 users
内更新用户通过查找并设置返回值。然而,console.log(overview[userI]);
不返回打印 null
.
var user = users.find(u => u.id===newUser.id);
var userI = users.findIndex(u => u.id===newUser.id);
user = null;
console.log(overview[userI]);
然后我运行了以下示例:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
let fruit = inventory.find(findCherries); // { name: 'cherries', quantity: 5 }
fruit.quantity = 6;
console.log(inventory);
然而,这一次inventory
确实按照我的预期更新为 cherries
现在值为 6。
为什么我在第一个示例中没有看到这种行为?
最佳答案
将 null 分配给先前具有对象引用作为值的变量,对该对象没有任何作用:
a = { test: 1 };
b = a;
b = null; // this does not influence the value of a.
在上面的示例中,b
首先被设置为共享 a
的值,但随后又再次走自己的路。这两个赋值都没有改变 a
的值。
但是当你改变一个对象时,对同一对象的所有引用当然会注意到这一点:
a = { test: 1 };
b = a;
b.test = 2;
console.log(a.test) // 2
因此,在您的示例中,如果您希望 users
数组的元素被 null
替换,则需要变异该数组:
var userI = users.findIndex(u => u.id===newUser.id);
if (userI > -1) users[userI] = null;
或者,您也可以使用 map
重新分配完整的数组:
var users = users.map(u => u.id===newUser.id ? null : u);
关于javascript - List.find 是否返回副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40062662/