0

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@dukegod What do you mean ? There's no closure here.
if i put var sum declaration inside 'for function',why there console 'NAN'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.