使用underscore.js迭代对象

11

我正在学习backbone.js,并且正在使用下面的示例在视图中迭代一些模型。第一个片段有效,而基于underscore.js的另一个不起作用。为什么?

// 1: Working
this.collection.each(function(model){ console.log(model.get("description")); });

// 2: Not working       
_.each(this.collection, function(model){ console.log(model.get("description")); });

我做错了什么,因为我自己看不出来?


2
任何反应吗?控制台中是否有错误? - Pointy
No. #2执行时没有任何输出到控制台。 - Industrial
2个回答

24

this.collection是一个实例,而this.collection.each是一种迭代适当对象(在集合实例的.models属性下)的方法。

有了这个说法,你可以尝试:

_.each(this.collection.models, function(model){ console.log(model.get("description")); });

这完全是没有意义的,因为this.collection.each是一个执行类似以下操作的函数:

function(){
return _.each.apply( _, [this.models].concat( [].slice.call( arguments ) ) );
}

那么你可以使用 this.collection.each ;P


1
感谢您解释为什么它没有起作用以及解决方案! - Industrial

2
此外,您可以尝试...
_.each(this.collection.models, function(model){
    console.log(model.get("description"));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接