Sum函数与递归和多个参数一起使用 [英] Sum function work with recursion and multiple arguments
本文介绍了Sum函数与递归和多个参数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个可以创建可与递归调用(例如(1)(2)(3)(4))和多个参数(例如(1、2、3、4))一起使用的sum函数的求和函数?
Is there a away to create a sum function that works with both recursive call (e.g (1)(2)(3)(4)), and multiple arguments (e.g (1, 2, 3, 4))?
喜欢这个:
sum(5, 5) // 10
sum(5)(5) // 10
谢谢.
推荐答案
You could return a function for next arguments and implement a toString
method.
function sum() {
var add = function (a, b) { return a + b; },
value = Array.prototype.reduce.call(arguments, add, 0);
function f() {
value = Array.prototype.reduce.call(arguments, add, value);
return f;
};
f.toString = function () { return value; };
return f;
}
console.log(sum(5, 5));
console.log(sum(5)(5));
console.log(sum(3, 4, 5)(6, 7));
这篇关于Sum函数与递归和多个参数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文