我有一个名为 Category
的对象,它使用一种方法来迭代产品数组 (Product
) 并返回满足 this.name 的实例===查询
条件:
function Category(products){
this.products = products;
this.findProductByName = function(query){
$(this.products).each(function(){
return this.name === query;
}
}
}
我的产品
(以防万一):
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;
});
};
}
关于javascript - 在 .each 迭代中返回一个对象 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557644/