本文介绍在不使用内置 `length` 属性的前提下,安全、准确地手动计算 javascript 数组长度的多种方法,并重点分析常见错误(如未初始化变量、错误的循环终止条件)及其修复方案。
你提供的代码陷入无限循环,根本原因有两点:
✅ 正确的手动计数方法应基于索引存在性判断。以下是几种可靠实现:
let array = [1, 2, 3, 4, 5];
let count = 0;
for (let i = 0; i < array.length; i++) {
// 注意:此处虽用了 array.length,但仅用于控制循环——若完全禁用 length,见方法二
count++;
}
console.log("length of array is " + count); // 输出:length of array is 5⚠️ 若严格禁止使用任何 length(包括循环中),则需依赖 in 操作符或 hasOwnProperty 判断索引是否存在:
let array = [1, 2, 3, 4, 5]; let i = 0; let count = 0; while (i in array) { count++; i++; } console.log("length of array is " + count); // 输出:length of array is 5
i in array 检查索引 i 是否为数组的有效自有属性(即 array[i] 存在且非稀疏空位),这是语义最准确的终止条件。
let array = [1, 2, 3, 4, 5];
let count = 0;
array.forEach(() => count++); // 无需参数,仅计数
console.log("length of array is " + count); // 输出:length of array is 5此方式无需关心索引,代码简洁,且天然避免越界问题,适合强调可读性与安全性的场景。
总之,手动计数的核心是明确“长度”的定义:即最大连续整数索引 + 1(标准数组),或自有数值索引的数量(稀疏数组)。选择 i in array 作为循环条件,是最符合 JavaScript 数组语义的安全方案。