【发布时间】: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