Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么过滤器不能给出和推送迭代相同的结果?_Javascript_Arrays_Ecmascript 6 - Fatal编程技术网

Javascript 为什么过滤器不能给出和推送迭代相同的结果?

Javascript 为什么过滤器不能给出和推送迭代相同的结果?,javascript,arrays,ecmascript-6,Javascript,Arrays,Ecmascript 6,我从以下原始数据中提取了一组对象: 可以这么说,数据如下所示: [0…99] 0 : 城市 : “纽约” 从2000年到2013年的增长 : "4.8%" 纬度 : 40.7127837 经度 : -74.0059413 人口 : "8405837" 等级 : "1" 状态 : “纽约” proto : 对象 1. : {城市:“洛杉矶”,从2000年到2013年的增长率:“4.8%”,纬度:34.0522342,经度:-118.2436849,人口:3884307,…} 我将其存储为const

我从以下原始数据中提取了一组对象:

可以这么说,数据如下所示:

[0…99] 0 : 城市 : “纽约” 从2000年到2013年的增长 : "4.8%" 纬度 : 40.7127837 经度 : -74.0059413 人口 : "8405837" 等级 : "1" 状态 : “纽约” proto : 对象 1. : {城市:“洛杉矶”,从2000年到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! :(
而不是这条线

oc.city.includes('las');
return oc.city.includes('las');
写这行

oc.city.includes('las');
return oc.city.includes('las');
您只是忘记了return语句,在本例中,它将返回未定义的

,而不是此行

oc.city.includes('las');
return oc.city.includes('las');
写这行

oc.city.includes('las');
return oc.city.includes('las');
您只是忘记了return语句,在本例中它将返回未定义的

删除{}

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');
});
进入


filter()
函数需要返回一个值。尝试
consttest2=JSON.LOCS.filter(loc=>loc.city.includes(“las”)
;您的
过滤器
状态在花括号之间。您需要
在此处返回检查的值,即使您使用的是箭头函数。您的
filter()
函数需要返回一个值。尝试
consttest2=JSON.LOCS.filter(loc=>loc.city.includes(“las”)
;您的
过滤器
状态在花括号之间。您需要
在此处返回检查值,即使您使用的是箭头函数。很高兴知道。为了清晰起见,我喜欢花括号,但是,是的,需要使用
return
Duh!:|很高兴知道。为了清晰起见,我喜欢花括号,但是,是的,需要使用
return
Duh!:|