javascript - Underscore.js:替换集合中的项目

标签 javascript arrays collections underscore.js

我已经使用 underscore.js 一周了,我真的很喜欢它。 但是,现在我想用另一个元素替换集合(vm.lists)中的单个元素。 我尝试执行以下操作:

_.each(vm.lists, function (el) {
    if (el.id == list.id)
        el = list;
});

和:

var l = _.findWhere(vm.lists, { id: list.id });
l = list;

但是它们都没有改变集合中的实际项目。我该如何正确地做到这一点?

最佳答案

你已经很接近了。问题是您仅替换指向该值的局部变量(ell),并且这不会修改初始列表。一个更简单的例子:

var list = [1, 2, 3];
var v = list[1];
v = 7; // v will now point to a new value, but list will stay intact [1, 2, 3]

与对象相同:

var olist = [{id: 1, v: 2}, {id: 4, v: 6}];
var obj = olist[0];
obj = {id: 8, v: 10}; // changes what obj points to, but does not affect olist[0]

var obj2 = olist[0];
obj2.v = 777; // olist[0] still points to the same object but the object is modified

olist[0] = {id: 8, v: 10}; // changes what olist[0] points to

所以基本上你有两个选择:

a) 更改vm.lists[index],使其指向一个新对象。您需要获取列表中对象的索引并执行 vm.lists[index] = newObject;。请注意,某些下划线谓词还为您提供索引 _.each(list, function (el, index) {});

b) 更改 vm.lists[index] 指向的对象,但您需要手动复制字段。例如,如果您的对象表示为 {id: id, values: [1, 2, 3], anotherField: data},您可以复制字段:

//el.id = list.id; // don't need this as you were searching by id
el.values = list.values;
el.anotherField = list.anotherField;

我认为第一个选择会更干净。

关于javascript - Underscore.js:替换集合中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024184/

相关文章:

javascript - axios 并发请求数 : any way to get the results from the successful requests even if some have failed?

java - 垃圾回收如何处理集合对象?

c# - 如何通过所有数据流 block 传播消息上限?

javascript - 使用 Api Gateway 创建 session 并重定向

javascript - JQuery 问题 "TypeError: $.getJSON is not a function"

javascript - 如何在特定的 wiki 页面中添加脚本标签?

arrays - 在 F# 中递归迭代数组

python - 为什么控制台卡在我用 python 解决 9X9 数独板的最后一个函数上?

arrays - 基于序列的排列枚举的变体

c# - .NET 中的随机和线程问题