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