使用underscore.js迭代对象

Ind*_*ial 10 javascript jquery backbone.js underscore.js

所以,我正在学习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")); });
Run Code Online (Sandbox Code Playgroud)

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

Esa*_*ija 23

this.collection是一个实例,this.collection.each而是一个迭代封面下正确对象的方法,它是.models集合实例的属性.

有了这个说你可以尝试:

_.each(this.collection.models, function(model){ console.log(model.get("description")); });
Run Code Online (Sandbox Code Playgroud)

这是一个完全没有意义this.collection.each的功能,类似于:

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

所以你不妨使用this.collection.each; P