List.find是否返回副本

时间:2016-10-15 18:23:31

标签: javascript

我希望通过查找和设置返回的值来更新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.

为什么我的第一个例子中没有看到这种行为?

1 个答案:

答案 0 :(得分:1)

将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,则需要 mutate 数组:

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