使用underscore.js迭代对象

所以,我正在学习backbone.js,并且正在使用下面的示例在视图中迭代某些模型。 第一个代码段工作,而另一个基于下划线.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")); }); 

我做错了什么,因为我自己看不到它?

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.

另外,你可以试试……

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