【发布时间】:2016-06-01 00:27:11
【问题描述】:
我有一个名为 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 时如何返回对象?
【问题讨论】:
-
$.each()机制忽略返回值(大部分)。你期望它做什么? -
使用 [].filter() 和 [].map() 而不是 each()
-
@Pointy 在满足条件时返回正确的
Product实例,以便我可以按名称搜索$someCategory内的产品。 “忽略返回值”是什么意思? -
returnfrom inside$.each()回调仅从该函数返回;它不会从您的findProductByName函数返回。 -
@Pointy ahhhhhhh,有道理。谢谢!
标签: javascript object iteration