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

JavaScript for循环触发TypeError:无法读取undefined的length属性

排查你的for循环TypeError问题

你提到代码没用到<=却触发了TypeError,确实,边界条件用<是没问题的,咱们从其他常见原因入手分析:

  • c或c.selection未定义/为空
    这是最常见的情况:如果变量c根本没被声明,或者c里不存在selection属性,那访问c.selection.length时就会抛出类似Cannot read properties of undefined (reading 'length')的TypeError。比如如果c是未初始化的变量,或者接口返回的c结构和你预期的不一样,就会出现这个问题。

  • c.selection不是数组/类数组对象,或部分元素为空
    就算c.selection存在,但如果它不是数组、NodeList这类带length属性的集合,而是单个对象或其他类型(比如字符串、数字),那访问.length会返回undefined,循环条件i < undefined会直接不执行循环;更可能的报错场景是:c.selection是类数组,但某些索引位置的元素是null或undefined,比如c.selection = [{}, null, {id: 1}],当i=1时,访问c.selection[i].id就会抛出Cannot read properties of null (reading 'id')的TypeError。

  • arr变量未初始化
    如果你直接用arr.push()但之前没声明并初始化arr(比如没写var arr = [];),那arr会是undefined,调用push方法时就会抛出Cannot read properties of undefined (reading 'push')的TypeError。

快速排查小技巧

你可以在循环前加几行调试代码,定位问题根源:

console.log('c的值:', c);
console.log('c.selection的值:', c.selection);
console.log('arr的值:', arr);

看控制台输出就能清楚到底是哪个变量出了问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:31:14