【问题标题】:Why is filter not giving same results as push with for..of iteration?为什么过滤器没有给出与 for..of 迭代相同的结果?
【发布时间】:2017-12-27 14:35:53
【问题描述】:

我从以下原始数据中提取了一组对象:https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json

可以这么说,数据看起来像这样:

[0 … 99] 0 : 城市 : “纽约” 成长_从_2000_到_2013 : “4.8%” 纬度 : 40.7127837 经度 : -74.0059413 人口 : “8405837” 秩 : “1” 状态 : “纽约” 原型 : 目的 1 : {城市:“洛杉矶”,growth_from_2000_to_2013:“4.8%”,纬度:34.0522342,经度:-118.2436849,人口:“3884307”,……}

我将其存储为const JSON_LOCS,在下面的代码中引用。

我正在尝试过滤此内容以查找包含某些特定测试的城市。我有两种不同的方法。一种方法似乎可行,但 Array.prototype.filter() 不行。

const test = [];
      for (let t of JSON_LOCS) {
        if (t.city.includes('las')) {
          test.push(t);
        }
      }

      const test2 = JSON_LOCS.filter(loc => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
        loc.city.includes('las');
      });
      console.log(test); // Yields a couple of results
      console.log(test2); // Always empty! :(

【问题讨论】:

  • 您的filter() 函数需要返回一个值。试试const test2 = JSON.LOCS.filter(loc => loc.city.includes("las"));
  • 您的filter 条件位于大括号之间。即使您使用箭头函数,您也需要在此处return 检查的值。

标签: javascript arrays ecmascript-6


【解决方案1】:

代替这一行

oc.city.includes('las');

写下这一行

return oc.city.includes('las');

你只是忘记了在这种情况下将返回未定义的 return 语句

【讨论】:

    【解决方案2】:

    删除 { }

    const test2 = JSON_LOCS.filter(loc => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
      loc.city.includes('las');
    });
    

    进入

    const test2 = JSON_LOCS.filter(loc => // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
      loc.city.includes('las'); // When not wrapped into {} it assumes its the return statement
    );
    

    【讨论】:

    • 很高兴知道。为了清楚起见,我喜欢花括号,但是,是的,需要使用return Duh! :|
    猜你喜欢
    • 2017-07-09
    • 2022-11-25
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2020-08-10
    • 2017-06-15
    相关资源
    最近更新 更多