【问题标题】:Returning an object in .each iteration - JavaScript在 .each 迭代中返回一个对象 - JavaScript
【发布时间】: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 内的产品。 “忽略返回值”是什么意思?
  • return from inside $.each() 回调仅从该函数返回;它不会从您的 findProductByName 函数返回。
  • @Pointy ahhhhhhh,有道理。谢谢!

标签: javascript object iteration


【解决方案1】:

你需要使用 jQuery 吗?能不能改用数组过滤方法...

function Category(products){
  this.products = products; 
  this.findProductByName = function(query){
    return this.products.filter(function(item){
      return item.name === query; 
    });
  };
}

【讨论】:

    【解决方案2】:

    您需要使用带有 return(或 map/reduce)的传统循环来让您的函数返回匹配的结果。 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 );
    });
    

    【讨论】:

    • 不错!谢谢!问题:那么当for loop 已经处理了迭代并返回vals 时,为什么还要使用each
    • 当您明确想要对数组中的每个项目执行操作时,它的语法很好,即为 name 属性添加前缀: $(this.products).each(function(i,el ){el.name = '我的' + el.name;});
    • 还有一些人喜欢 jquery 而不是原生 javascript。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多