admin管理员组文章数量:1279085
function sumArray(numbers){
var sum;
for(var i in numbers){
sum += numbers[i];
}
return sum;
}
console.log(sumArray([1,2,3,4,5]));
Hi all,
The oute is NaN. However, if I initialize sum with sum = 0, the oute 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?
Thanks
function sumArray(numbers){
var sum;
for(var i in numbers){
sum += numbers[i];
}
return sum;
}
console.log(sumArray([1,2,3,4,5]));
Hi all,
The oute is NaN. However, if I initialize sum with sum = 0, the oute 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?
Thanks
Share Improve this question asked Mar 15, 2016 at 4:46 SeanSean 9811 gold badge9 silver badges19 bronze badges 2- undefined+anything = NaN – juvian Commented Mar 15, 2016 at 4:47
-
1
Initialize
var sum = 0;
– Tushar Commented Mar 15, 2016 at 4:48
4 Answers
Reset to default 4When a variable is declared within current scope, it is initialized with undefined
value.
var sum; // is initialized with undefined
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:
undefined
+ 1NaN
+ 1NaN
Please check this article for more info about the addition operator (example 7).
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;
});
when you create var sum;
it's value is undefined [default]
so when you keep adding to undefined you get NaN
[Not a Number]
but if you initialize as var sum=0;
then you are adding numbers to 0 so you get correct output
try
console.log(undefined+1);
you get NaN but
if you do
console.log(0+1);
then you get 1
This is because you have not initialized sum
. So sum+
will try to add to undefined
.
function sumArray(numbers){
var sum=0; // sum="" if you want output as 12345
for(var i in numbers){
sum += numbers[i];
}
return sum;
}
console.log(sumArray([1,2,3,4,5]));
jsfiddle
The reason behind is very clear. When JavaScript finds any "undefined" or "unexpected" error then it returns NaN.
Where else in your second condition where you added sum=0 ,it already made a value of it then what ever you did it was addition to that value.
本文标签: javascript variable initialization shows NaNStack Overflow
版权声明:本文标题:javascript variable initialization shows NaN - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741214312a2359747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论