返回传递给函数的所有参数的总和

时间:2016-07-25 11:40:31

标签: javascript

一种方法是使用参数。我可以循环遍历arguments数组,并且可以返回传递的所有参数的总和。

function sum(){
  var sum =0; 
  for(var i=0;i<arguments.length;i++){
     sum += arguments[i];
  }
   return sum;
}
sum(1,2); // returns 3
sum(1,2,3); // returns 6

如果不使用循环,还有其他方法吗?

7 个答案:

答案 0 :(得分:8)

其他人提供的答案是将arguments冗余复制到稍后会丢弃的数组。

相反,你可以一步完成所有事情:

function sum() {
    return Array.prototype.reduce.call(arguments, function(a, b) {
        return a + b;
    }, 0);
}

如果使用ES2015是一个选项,您可以稍微更好(主观)实现:

const sum = (...args) => [...args].reduce((a, b) => a + b, 0);

答案 1 :(得分:1)

正如zerkms所说,你可以使用reduce这样的功能

alert([1, 2].reduce((a, b) => a + b, 0));
alert([1, 2, 3].reduce((a, b) => a + b, 0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:1)

使用Array.prototype.slice.callarguments转换为数组,并使用reduce来汇总数字。

 function sum(){
   var total =  Array.prototype.slice.call(arguments).reduce(function(a, b) { 
   return a + b; 
   }, 0);
   return total;
}
console.log(sum(1,2)); // returns 3
console.log(sum(1,2,3)); // returns 6

演示:https://jsfiddle.net/wru8mvxt/10/

答案 3 :(得分:0)

Arguments是javascript中的对象数组。您可以使用reduce属性转换为sum它是元素。

function sum() {
  var args = Array.prototype.slice.call(arguments);
  var sum = args.reduce(function(a, b) {
    return a + b;
  })
  return sum;
}


console.log(sum(1, 2)); // returns 3
console.log(sum(1, 2, 3)); // returns 6

您还可以使用forEach方法

JSFIDDLE

答案 4 :(得分:0)

您可以通过以下方式轻松实现

function sum(){
  var total =  0;
  for(var i=0; i<arguments.length; i++){
     total += arguments[i];
  }
  return total;
}
console.log(sum(1, 2)); // returns 3
console.log(sum(1, 2, 3)); // returns 6

同样使用Array.prototype.reduce.call()方法。

function sum(){
   var total =  Array.prototype.reduce.call(arguments, function(a, b) { 
   return a + b; 
   });
   return total;
}      
console.log(sum(1, 2));    // returns 3
console.log(sum(1, 2, 3));   // returns 6

答案 5 :(得分:0)

这是我使用ES15的解决方案:

function sumArgs() {
    return [...arguments].reduce((acc,next)=>acc+next, 0)
};

console.log(sumArgs(1,2,3,4,5));

答案 6 :(得分:0)

rest 参数的单行:

const sum = (...args) => args.reduce((a, b) => a + b);

sum(1, 3, 5, 7, 9); // 25
相关问题