如何使用_.each()从集合中获取元素

时间:2018-03-26 15:09:38

标签: underscore.js

我有一个模型的骨干集合,现在我想从集合中访问每个模型并使用_.each()做一些事情,在查看下划线文档之后,我想出了第一个

_.each(this.someCollection, function(element) {
    console.log(element);
}

但是元素是undefined ...,做了一些进一步的阅读,并在第二次尝试:

_.each(this.someCollection, function(element, index, list) {
    console.log(list.at(index);
}

这似乎可以工作并获得我想要的每个模型,但是从每个迭代中获取元素对我来说似乎非常复杂。有更好/更优雅的方式吗?什么是第一个参数“元素”有益?人们会认为它应该实际上做我需要的......

1 个答案:

答案 0 :(得分:0)

this.collection不返回models array,而是包含特定集合属性的对象,如

{length:2, models:(2) [s,s], _byId:{c119: s, c123: s}, _events:{…}, _listenId:"l1"}

如果要访问集合的模型,请使用models属性,该属性返回一组模型

_.each(this.someCollection.models, function(model) {
    console.log(model.toJSON());
    console.log(model.get('someProperty');
}

或在

等集合上直接使用toJSON()
_.each(this.someCollection.toJSON(), function(model) {
    console.log(model);
    console.log(model.someProperty);
}