【问题标题】:how to write a single function named `add`. Such that once it has received 2 arguments, it returns the sum of the 2 values如何编写一个名为 `add` 的函数。这样一旦它收到 2 个参数,它就会返回 2 个值的总和
【发布时间】:2019-02-05 21:05:49
【问题描述】:

如何编写一个名为add 的函数。这样一旦它收到 2 个参数,它就会返回 2 个值的总和。假设所有值都是数字。:

例如 // add(1, 2) = 3

// 加(1)(2) = 3

// add()(1)()(2) = 3

// add()(1)(2) = 3

【问题讨论】:

  • 请向我们展示您的尝试。
  • function calcSum(a,b){ var ab = function (b) { return a+b; } if(typeof a == 'undefined'){ return ab; } if(typeof b == 'undefined'){ return ab; } else { return ab(b); } }
  • 谢谢,希望我的回答对您有所帮助

标签: javascript ecmascript-6 closures


【解决方案1】:

太简单了:

 const curry = (fn, ...previous) => (...args) => args.length + previous.length >= fn.length ? fn(...previous, ...args) : curry(fn, ...previous, ...args);

 const add = curry((a, b) => a + b);

【讨论】:

  • 你能解释一下吗?
【解决方案2】:

我试过了

function calcSum(a,b){ var ab = function (b) { return a+b; } if(typeof a == 'undefined'){ return ab; } if(typeof b == 'undefined'){ return ab; } else { return ab(b); } }

这看起来还不错 - 它适用于 calcSum(1,2)calcSum(1)(2)。但是,您没有正确处理未传递任何内容(或 undefined)的情况:

  • calcSum() 应该返回一个仍然需要两个参数的函数
  • calcSum(1)() = ab() 应该返回一个仍然需要一个参数的函数

您已经匹配了第一种情况,但是您返回了 ab(只接受一个值)而不是 calcSum(接受两个值的函数)。要解决此问题,请使用

function calcSum(a,b){
    var ab = function(b) {
        if (typeof b == 'undefined') return ab;
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        else return a+b;
    }
    if (typeof a == 'undefined') return calcSum;
//                                      ^^^^^^^^
    if (typeof b == 'undefined') return ab; // actually you don't need this, ab(b) already handles this case as well now
    else return ab(b);
}

【讨论】:

  • 感谢您让我了解如何思考以及我错过了什么。还有如何使它不仅适用于 2 个参数,而且适用于 'n' 个参数?
  • @sampathNeeru 这真的很难(而且不是特别有用),因为您永远不知道何时返回另一个函数或结果。不过有some solutions
【解决方案3】:

您对此建议有何看法:

function add(){
  return Array.from(arguments).reduce((accumulator, currentValue) => accumulator + currentValue)
}

// you can also add as many argument you want.
const b = add(1,2,3,4); // 10

【讨论】:

    【解决方案4】:
    const add = (...toAddArr) => {
        let result = 0;
        for (let toAddNr of toAddArr) {
            result += toAddNr;
        }
        return result;
    }
    

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

    此示例使用rest operator 获取无限参数并将其作为数组传递,并使用for/of loop 对其进行迭代。

    【讨论】:

      【解决方案5】:
      let add = (...a)=>a.length==2 ? a[0]+a[1] : (...b)=>add(...a.concat(b));
      

      这个想法很简单......我们声明一个可变参数函数,如果我们有两个元素,那么我们就完成了(并返回总和)否则我们返回一个新的可变参数函数,它将收集更多元素并递归调用函数本身传递已经得到的 a 与新元素 b 连接的内容。

      【讨论】:

      • 你能解释一下吗?
      • @sampathNeeru:添加了解释
      猜你喜欢
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2011-09-24
      • 2012-02-27
      • 2020-01-29
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多