javascript 使用 underscore.js 迭代对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8421238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:23:45  来源:igfitidea点击:

Iterating objects with underscore.js

javascriptjquerybackbone.jsunderscore.js

提问by Industrial

So, I am learning out backbone.js and are currently iterating over some models in a view with the below example. The first snippet works, when the other underscore.js-based one doesn't. Why?

因此,我正在学习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")); });

What am I doing wrong, as I can't see it by myself?

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

回答by Esailija

this.collectionis an instance while this.collection.eachis a method that iterates the proper object under the covers which is the .modelsproperty of a collection instance.

this.collection是一个实例 whilethis.collection.each是一个方法,它在掩护下迭代适当的对象,这是.models集合实例的属性。

With this said you can try:

有了这个,你可以尝试:

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

Which is completely pointless as this.collection.eachis a function that does similar to:

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

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

So you might as well use this.collection.each;P

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

回答by coliath

Also, you could try...

另外,你可以试试...

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