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

调用API过滤数据推入新数组后,元素为何为undefined?

问题原因

这是异步代码执行顺序导致的问题:

  • getData()是异步请求(返回Promise),.then()里的回调函数要等API请求完成、拿到数据后才会执行。
  • 你写在.then()外面的console.log("typeof child:", typeof (filteredFeatures[0]))是同步代码,会在API请求还没返回结果的时候就先执行——这时候filteredFeatures还是空数组,取索引0自然是undefined。
解决方案

方案1:把依赖过滤后数组的逻辑放到.then()内部

把需要访问filteredFeatures的代码移到异步回调里,确保数据已经填充:

function filterDataAtSource(city, vacTypeFilters) {
    var filteredFeatures = [];

    getData().then(function (geojson) {
        var features = geojson.features
        features.forEach(element => {
            if (element.properties.City === city) {
                console.log("type of element :", typeof (element));
                filteredFeatures.push(element);
            }
        });
        // 此时filteredFeatures已经有数据了
        console.log("typeof child:", typeof (filteredFeatures[0])); 
    })
}

方案2:用async/await简化异步代码

async/await能让异步代码看起来像同步执行,逻辑更清晰:

async function filterDataAtSource(city, vacTypeFilters) {
    var filteredFeatures = [];

    // 等待getData()返回结果
    const geojson = await getData();
    var features = geojson.features
    features.forEach(element => {
        if (element.properties.City === city) {
            console.log("type of element :", typeof (element));
            filteredFeatures.push(element);
        }
    });
    // 这里能正常访问到过滤后的数组
    console.log("typeof child:", typeof (filteredFeatures[0]));
}

额外优化:用filter方法简化过滤逻辑

不需要手动forEach+push,可以直接用数组的filter方法一步得到结果:

async function filterDataAtSource(city, vacTypeFilters) {
    const geojson = await getData();
    const filteredFeatures = geojson.features.filter(element => 
        element.properties.City === city
    );
    console.log("typeof child:", typeof (filteredFeatures[0]));
    // 如果需要返回结果,直接return即可(调用时要加await或.then)
    return filteredFeatures;
}

内容的提问来源于stack exchange,提问作者WilliamHe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:15:31