You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript filter函数无法过滤JSON人口数据问题求助

问题修复方案

核心问题分析

  1. 异步执行时机错误:fetch是异步操作,你当前的sort和filter代码在数据还未加载完成时就已执行,此时cities是空数组,导致gofilter被赋值为空数组(你看到的undefined大概率是控制台输出的误解)。
  2. sort回调缺少返回值:排序回调中的三元表达式没有return,导致回调返回undefined,Array.sort会使用默认排序规则,逻辑不符合预期。
  3. 字段类型不匹配: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:54:57