JavaScript filter函数无法过滤JSON人口数据问题求助
问题修复方案
核心问题分析
- 异步执行时机错误:
fetch是异步操作,你当前的sort和filter代码在数据还未加载完成时就已执行,此时cities是空数组,导致gofilter被赋值为空数组(你看到的undefined大概率是控制台输出的误解)。 - sort回调缺少返回值:排序回调中的三元表达式没有
return,导致回调返回undefined,Array.sort会使用默认排序规则,逻辑不符合预期。 - 字段类型不匹配:JSON中的
population是字符串类型,直接与数字比较可能出现异常。
修复后的代码
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; let cities = []; fetch(endpoint) .then(jsonout => jsonout.json()) .then(pushdata => { cities.push(...pushdata); // 数据加载完成后再执行排序和筛选 let sortgo = cities.sort((a, b) => { // 转成数字再比较 const firstone = Number(a.population); const nextone = Number(b.population); // 必须return排序结果 return firstone > nextone ? -1 : 1; }); let gofilter = cities.filter(n => Number(n.population) > 100000); console.table(sortgo); console.table(gofilter); });
关键修改点
- 将
sort和filter逻辑移入fetch的最后一个then回调中,确保在数据完全加载后执行。 - 给
sort回调的三元表达式添加return,明确返回排序比较结果。 - 使用
Number()将population字段转为数字类型,避免字符串与数字比较的异常。
内容的提问来源于stack exchange,提问作者Crying_super_noob
相关产品推荐
相关产品推荐

