英文:
How can I manually count the length of an array?
问题
我试图找到一个没有内置长度属性的数组的长度。这样做对吗?它进入了无限循环。
let array = [1, 2, 3, 4, 5];
let i;
let count = 0;
while (array[i] !== undefined) {
console.log(array[i]);
i++;
count++;
}
console.log("数组的长度是" + count);
英文:
I'm trying to find length of array without built-in length property. Is this a right way? It is going in infinite loop.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array = [1, 2, 3, 4, 5];
let i;
let count = 0;
while (array[i] != 'undefined') {
console.log(array[i]);
i++
count++;
}
console.log("length of array is" + count);
<!-- end snippet -->
答案1
得分: 1
你的代码将导致无限循环!!
首先,你已声明了变量 i
,但没有赋初值。这意味着 i
将是 undefined
,当你将其用作索引访问 array[i]
时,它将始终是 undefined
,从而导致无限循环。
其次,在你的 while 循环条件中,你正在检查 array[i] != 'undefined'
。这个比较应该是 array[i] !== undefined
(不要在 undefined
周围加引号)。在这种情况下,undefined 关键字不应被视为字符串。
let array = [1, 2, 3, 4, 5];
let i = 0;
let count = 0;
while (array[i] !== undefined) {
console.log(array[i]);
i++;
count++;
}
console.log("数组的长度是 " + count);
英文:
Your code will result in an infinite loop !!
Firstly, you have declared i
but have not initialized it with a value. This means i
will be undefined
, and when you use it as an index to access array[i]
, it will always be undefined
, resulting in an infinite loop.
Secondly, in your while loop condition, you are checking array[i] != 'undefined'
. This comparison should be array[i] !== undefined
(without the quotes around undefined). The undefined keyword should not be treated as a string in this case.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array = [1, 2, 3, 4, 5];
let i = 0;
let count = 0;
while (array[i] !== undefined) {
console.log(array[i]);
i++;
count++;
}
console.log("Length of array is " + count);
<!-- end snippet -->
I hope I helped you learn something new today
答案2
得分: 1
Your way can work with the fixes proposed by zoldxk. However, a modern forEach()
loop seems simpler here. You don't need to bother with indexes.
let array = [1, 2, 3, 4, 5];
let count = 0;
array.forEach(element => {
count++;
});
console.log("length of array is " + count);
console.log('array.length is', array.length);
英文:
Your way can work with the fixes proposed by zoldxk. However, a modern forEach()
loop seems simpler here. You don't need to bother with indexes.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array = [1, 2, 3, 4, 5];
let count = 0;
array.forEach(element => {
count++;
});
console.log("length of array is " + count);
console.log('array.length is', array.length);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论