簡體   English   中英

使用underscore.js迭代對象

[英]Iterating objects with 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")); });

我做錯了什么,因為我自己看不到它?

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"));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM