[英]Returning an object in .each iteration - JavaScript
我有一個名為Category
的對象,該對象使用一種方法來遍歷產品數組( Product
)並返回一個滿足this.name === query
條件的實例:
function Category(products){
this.products = products;
this.findProductByName = function(query){
$(this.products).each(function(){
return this.name === query;
}
}
}
我的Product
(以防萬一):
function Product(name){
this.name = name;
}
然后,我使用產品創建Category
的實例:
var $someCategory = new Category(
[
new Product('foo'),
new Product('bar')
]
)`
當我打電話時:
$someCategory.findProductByName('foo'); // 'undefined'
即使:
...
this.findProductByName = function(query){
$(this.products).each(function(){
console.log(this.name === query); // returns 'true'
}
}
...
滿足this.name === query
時,我該怎么做才能返回對象?
您需要使用jQuery嗎? 您能否改用數組過濾器方法...
function Category(products){
this.products = products;
this.findProductByName = function(query){
return this.products.filter(function(item){
return item.name === query;
});
};
}
您需要使用帶有返回(或映射/歸約)的傳統循環,以使函數返回匹配的結果。 每個函數都會對數組中的每個元素執行一個操作,它將不會執行過濾,並且會忽略返回的值。
嘗試這個:
this.findProductByName = function(query) {
for (var i = 0; i < this.products.length; i++) {
if (this.products[i].name === query)
{
return this.products[i];
}
}
}
僅供參考,通常將參數傳遞到each()
函數中,該函數標識使用時要迭代的當前元素。這有助於消除“ this”的范圍問題
$(this.products).each(function( index, value ) {
alert( index + ": " + value );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.