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

如何手动计算数组长度?不使用length属性的方法为何无限循环?

问题分析与修正

你的代码思路方向是对的,但有几个明显错误导致无限循环:

  • 变量i未初始化:你只声明了i但没赋值,初始值是undefined。访问array[i]时,JS会把undefined转为字符串"undefined",相当于你一直在访问array["undefined"],这个位置本来就不存在值,所以判断条件永远成立。
  • 判断条件错误:你把undefined当成字符串'undefined'来比较了,数组越界访问得到的是原始值undefined,不是字符串,所以array[i] != 'undefined'永远为true,循环停不下来。
  • 缺少初始索引值:遍历数组应该从索引0开始,i得先设为0。

修正后的代码

let array = [1, 2, 3, 4, 5];
let i = 0; // 初始化索引为0
let count = 0;

while (array[i] !== undefined) { // 用严格不等于判断原始undefined
  console.log(array[i]);
  i++;
  count++;
}

console.log("length of array is " + count);

补充:更严谨的写法

上面的方法有个小问题:如果数组里本身就有undefined元素,会提前终止循环。可以改用判断索引是否在数组的键集合里,更准确:

let array = [1, undefined, 3, 4, 5];
let i = 0;
let count = 0;

while (i in array) { // 判断当前索引是否是数组的自有属性
  console.log(array[i]);
  i++;
  count++;
}

console.log("length of array is " + count);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:12:34