一、问题 实现 sum 这样的一个函数
console.log(sum(1,2,3)); //6
console.log(sum(2,3)(2)); //7
console.log(sum(1)(2)(3)(4)); //10
console.log(sum(2)(4,1)(2)); //9
二、解法如下(注意 node 运行结果不一样。还有打印出来 会带有 f 前缀,但是 明明返回的(acc)就是一个 Number 类型(用typeof去判断的)
function sum(){
var acc = Array.from(arguments).reduce((acc, cur) => {
return acc+cur;
},0);
function fn() {
let next = Array.from(arguments).reduce((acc, cur) => {
return acc+cur;
},0)
acc += next;
return fn; //千万别忘了这一行!!
}
fn.toString = () => acc; //需要进行转换
return fn;
}
console.log(sum(1,2,3)); //6
console.log(sum(2,3)(2)); //7
console.log(sum(1)(2)(3)(4)); //10
console.log(sum(2)(4,1)(2)); //9