如何使用while循环求和保存为JavaScript中数组的数字 [英] How to sum numbers saved as array in JavaScript with while loop
问题描述
错误在哪里?我想对数组中的每个数字求和。警报显示 NaN
。
Where is the mistake? I want to sum every number in the array. The alert says NaN
.
var numbers = [10, 42, 5, 87, 61, 34, 99];
var i = 0;
var e = 0;
while(i <= numbers.length) {
e = e + numbers[i];
i++;
}
alert(e);
推荐答案
问题出在数组长度中您正在检查因为数组索引以0开头。这样做时:
The problem is in array length You are checking because array index starts with 0. In that way when doing:
i <= numbers.length
您正在检查[0:10,1:42,2:2:5,3:87,4:61,5:34,6 :99,7:???],因为数字长度为7。要解决该问题,只需执行以下操作:
You are checking [0: 10, 1: 42, 2: 5, 3: 87, 4: 61, 5: 34, 6: 99, 7:???] because numbers length is 7. To solve it just do:
i < numbers.length
其中,您不检查数组中不存在的数字。
where You don't check non existing number in array.
这是我们在学校的想法:
Here is how we were thought in school:
//main code//
var numbers = [10, 42, 5, 87, 61, 34, 99];
var result = sumIntArray(numbers);
//end of main code//
function sumIntArray(array){
var result = 0;
for (var i = 0; i < array.length; i++) {
if (array[i].isInteger()) {
result += array[i];
} else {
if (i === 0) {
alert("1st object in array is not number, will skip...");
}
else if (i === 1) {
alert("2nd object in array is not number, will skip...");
}
else if (i === 2){
alert("3rd object in array is not number, will skip...");
}
else {
alert((i+1).toString() + "th object in array is not number, will skip...");
}
}
}
return result;
}
for 循环会添加此i ++一会儿循环,使代码更加清晰。
无需在主代码中声明 i :)
The for loop adds this i++ You make in a while loop and makes code a bit more clear.
No need for declaring i in main code :)
- 始终使函数简化主代码。
- 使即使有人想破坏逻辑也不会出错的函数。
- Always make functions to simplify main code.
- Make function that will never make mistake even if somebody wants to break The logic.
虽然不要让学校放假,但您的创造力却很棒! :)
Although don't make school break Your creativity, Your code is great! :)
这篇关于如何使用while循环求和保存为JavaScript中数组的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!