我想知道使用 'while loop' 的'array'长度,但代码显示错误



var arr = [1, 2, 3, 4, 5]
var length = 0 while (true) { if (arr.charAt(length) == '') { break } else { length++ } } console.log(length)

arr.length

是查找数组长度的建议方法。

如果您仍然想使用while循环来查找长度。使用以下代码

const arr = [1, 2, 3, 4, 5];
let i = 0;
while (arr[i]) {
i++;
}
console.log(i);

最新更新