返回传递给函数的所有参数的总和 [英] Return sum of all arguments passed to function

查看:62
本文介绍了返回传递给函数的所有参数的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One way is to use arguments. I can loop over the arguments array and can return the sum of all the arguments passed.

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

还有其他方法可以不使用循环吗?

Is there any other way to do it without using loop?

推荐答案

其他人提供的答案是将 arguments 的冗余副本复制到即将被抛弃的数组中.

Other people provided answers with redundant copying of arguments to an array that is to be thrown away in a moment.

相反,您可以一步完成所有操作:

Instead you can do everything in one step:

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

如果可以选择使用ES2015,则可以实现更好的(主观的)实现:

If using ES2015 is an option you can have slightly nicer (subjective) implementation:

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

这篇关于返回传递给函数的所有参数的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆