javascript变量初始化显示NaN [英] javascript variable initialization shows NaN
问题描述
function sumArray(numbers){
var sum;
for(var i in numbers){
sum += numbers[i];
}
return sum;
}
console.log(sumArray([1,2,3,4,5]));
大家好,
结果为 NaN .但是,如果我使用 sum = 0 初始化sum,则结果为15.为什么JS无法识别数组中的值类型,并为我进行初始化?为什么在第一种情况下会返回 NaN ?
The outcome is NaN. However, if I initialize sum with sum = 0, the outcome is 15. Why JS does not recognize the value type in the array and do the initialization for me? Why does it return NaN in the first case?
谢谢
推荐答案
在当前范围内声明变量时,将使用 undefined
值对其进行初始化.
When a variable is declared within current scope, it is initialized with undefined
value.
var sum; // is initialized with undefined
在 for
循环中,加法 sum + =数字[i]
实际上是在执行 undefined + 1
操作.由于两个操作数都不是字符串类型,因此它们将转换为数字:
In the for
loop, the addition sum += numbers[i]
is actually doing an undefined + 1
operation. Because both operands are not string types, they are converted to numbers:
-
未定义
+ 1 -
NaN
+1 -
NaN
undefined
+ 1NaN
+ 1NaN
请查看此文章,以获取有关加法运算符的更多信息(示例7)
Please check this article for more info about the addition operator (example 7).
当然,要解决此问题,只需将其初始化为0:
Of course, to solve this problem just initialize it with 0:
var sum = 0;
我也将这些项目简单化:
Also I would sum the items simpler:
var sum = [1,2,3,4,5].reduce(function(sum, item) {
return sum + item;
});
这篇关于javascript变量初始化显示NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!