Reputation: 601
today,i want to get a sum number,but get a wrong number.
function fun(a,b,c){
var l = arguments.length;
console.log('length'+l);
for(var i=0;i<l;i++){
var sum;
console.log(arguments[i]);
sum= sum+arguments[i];
}
return sum;
}
var p= fun(1,2,3);
console.log(p);
p is 'NaN'
if change the fun(1,2,3) to fun(1,2,3,4,5),is there some differences?
Upvotes: 0
Views: 50
Reputation: 382102
The problem is you're not initializing sum
, so you're adding to undefined
the first time (undefined+1
gives NaN
), then to NaN
.
Change
for(var i=0;i<l;i++){
var sum;
console.log(arguments[i]);
sum= sum+arguments[i];
}
to
var sum = 0;
for(var i=0;i<l;i++){
console.log(arguments[i]);
sum= sum+arguments[i];
}
Note that the var sum
declaration is hoisted to the start of the function.
Upvotes: 4