【问题标题】:How to add the function n number of arguments in Javascript? add(3)(8)(6)(10) [duplicate]如何在Javascript中添加函数n个参数?添加(3)(8)(6)(10)[重复]
【发布时间】:2018-04-03 03:44:45
【问题描述】:

我需要添加函数 n 个参数。示例:add(3)(8)(6)(10)。

如果只有 2 个参数,我们可以像这样添加代码。添加(4)(5)

function add(x){
    return function(y){
       return x+y;
    }
}
add(4)(5)

如果是n个参数,我们该怎么做呢?

【问题讨论】:

标签: javascript


【解决方案1】:

我越接近你问的就是这个;

function add(x){
    var next = function(y){
       return add(x + y)
    }

    next.result = x
    return next
}

console.log(add(4)(5).result)
console.log(add(4)(5)(1)(5).result)
console.log(add(3).result)

这是使用对象的一种稍微不同的方法,IMO 它比add(1)(2)(3) 更具可读性,因为很清楚您在后​​续步骤中执行的操作。此外,这种方法允许使用更多操作进行扩展,例如减号。

class Add {
    constructor (value) {
        this.value = value
    }

    add (anotherValue) {
        return new Add(this.value + anotherValue)
    }

    result () {
        return this.value
    }
}

function add (value) {
    return new Add(value)
}

var result = add(3).add(5).add(10).result()
console.log(result) // 18

【讨论】:

  • 提问者想要函数的部分应用,而不是方法链。
  • 是的,但他想要的是不可能的(见 Ryan 评论)。这是实现相同结果的更好方法,恕我直言。
  • 恕我直言,不要以add() 开始链。可能立即执行calculator.startWith(3).add(5) 之类的操作更可读Understandable。话虽如此,这仍然很酷。
  • 很好的建议,@ErikPhilips 除了那些大写字母哈哈 :)
  • 我主要是用 C# 编写程序,我不假思索地做 ;)
【解决方案2】:

如果事先不知道n,我可以断然说这是不可能的。如果n 是固定的,您可以执行类似的操作(例如,n 是 4):

const add = first => second => third => fourth => first + second + third + fourth.

如果你想让n变得灵活,你最好的选择是这个

const add = (...additives) => {
  let result = 0;
  for (const additive of additives) {
    result += additive;
  }
  return result;
}

【讨论】:

    【解决方案3】:

    正如Ryan 在他的评论中建议的那样:add(3)(8)(6)(10) 是不可能的。

    试试这个解决方法:

    function add() {
      var sum = 0;
      for (var i = 0; i < arguments.length; i++) {
        sum = sum+arguments[i];
      }
      return sum;
    }
    
    var res = add(3, 8, 6, 10);
    console.log(res);

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 2016-06-12
      相关资源
      最近更新 更多