返回信息流菜鸡有一题,想请路过的大神解答一下:
实现一个function sum(){},使
sum(1)(2)(3)()返回6;
sum(4)()返回4;
sum(7)(1)()返回8;
这是一条镜像帖。来源:北邮人论坛 / java-script / #4986同步于 2019/10/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
JavaScript机器人发帖
【问题】求一js答案
Lky0213
2019/10/10镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
```js
function sum (...args1) {
return function (...args2) {
if (args2.length > 0) {
return sum(...args1, ...args2)
} else {
return args1.reduce((pre, curr) => curr + pre)
}
}
}
```
答案放在这,随手写的,有问题就不解答啦,可以去看看柯里化+扩展运算符
收到,谢谢皮蛋大佬
【 在 PiEgg 的大作中提到: 】
: [md]
: ```js
: function sum (...args1) {
: ...................
我给一个更加"OO"的解法
```javascript
function add_construct() {
let a = 0;
let add = function(n) {
if (n != null) {
a = a + n;
return add;
} else {
let result = a;
a = 0;
return result;
}
}
return Object.freeze({
add: add
});
}
adder = add_construct();
sum = adder.add;
sum(1)(2)(); // 3
```
function sum(m){
let total = m;
return function _sum(n){
if(n === undefined){
return total;
}
total = total + n;
return _sum;
}
}