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

数组已填充但length为0且forEach无法遍历的技术问题

数组显示有元素但length为0且无法遍历的问题

我遇到一个奇怪的问题:网上现有解答大多围绕异步等待场景展开,但这里完全不适用——源JSON已经提前存在于HTML中。明明数组里能看到元素,可它的length属性显示为0,用forEach也没法遍历它。

以下是相关代码和控制台输出情况:

// 容器类
public inspectionTypes: SelectionOption[] = [];

// 后续代码
public initializeInspectionTypes(types: any[]) {
    if (types) {
        types.forEach(t => {
            this.inspectionTypes.push(t);
        });
    }
}
// 其他类
console.debug('Type:', typeof container.inspectionTypes);
console.debug('Is Array:', Array.isArray(container.inspectionTypes));
console.debug('Length:', container.inspectionTypes.length);
console.debug(container.inspectionTypes);

container.inspectionTypes.forEach(option => {
    console.debug(option);
    // this.inspectionTypes().push(option);
});

控制台打印时,数组的length显示为0,但直接打印数组却能看到里面已填充元素。就算调换日志打印顺序,先输出数组再输出length,这个问题依然存在,相关控制台截图如下:

控制台截图1
控制台截图2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:42:10