admin管理员组

文章数量:1333201

I have a large numbers of variables. What is the most correct way to calculate the sum. Below is the static way. .What if the numbers will increase to N times?

function abc(a,b,c,d){
  alert(a+b+c+d); 
}
abc(2,3,4,5);

I have a large numbers of variables. What is the most correct way to calculate the sum. Below is the static way. .What if the numbers will increase to N times?

function abc(a,b,c,d){
  alert(a+b+c+d); 
}
abc(2,3,4,5);
Share Improve this question asked Jul 27, 2013 at 19:46 user2265582user2265582 2
  • 8 Why don't you use an array instead of a large number of variables? Will make adding up easy. – Patrick Kostjens Commented Jul 27, 2013 at 19:47
  • 1 Where are the numbers ing from? User input? – grandinero Commented Jul 27, 2013 at 19:49
Add a ment  | 

4 Answers 4

Reset to default 4
function abc(){
    return Array.prototype.reduce.call(arguments, function(a,b) {
        return a + b;
    }, 0);
}

We can reduce the verbosity by binding .reduce as the this value of .call.

var reduce = Function.call.bind([].reduce);

Then it's just:

function abc(){
    return reduce(arguments, function(a,b) {
        return a + b;
    }, 0);
}

You could use arguments

function abc(){
  var total = 0;
  for( var i = 0; i < arguments.length; i++) {
     total += arguments[i];
  }
  alert(total);
}

abc(1, 2, 3, 4, 5, 6, 7);

Demo

OR

function abc( args ){
  var total = 0;
  for( var i = 0; i < args.length; i++) {
     total += args[i];
  }
  alert(total);
}
abc([1, 2, 3, 4, 5, 6, 7]);

Demo

The best way would be to use the latter.

To accept a limitless number of arguments automatically, use the arguments property.

function sum() { // javascript functions can accept more arguments than specified
  var total = 0;
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

Bear in mind that this might not actually be much shorter or more-readable than just calling "a + b + c + d" in your original code.

Here is a shorter version using the Array.reduce() mand.

function abc() {
   alert([].reduce.call(arguments, function(a, b) { return a + b; }));
}
abc(2,3,4,5);

本文标签: functionThe best way to sum up lots of numbers using JavaScriptStack Overflow