在 .each 迭代中返回一个对象 - 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; 
    });
  };
}

您需要使用带有返回(或映射/减少)的传统循环,以使函数返回匹配的结果。each 函数对数组中的每个元素执行一个操作,它不会执行筛选,并忽略返回的值。

试试这个:

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

最新更新