函数接受可变数量的链式调用,如`add(1)(2)(3)(4)` [英] Function to accept variable number of chained calls like `add(1)(2)(3)(4)`

查看:145
本文介绍了函数接受可变数量的链式调用,如`add(1)(2)(3)(4)`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个可以接受任意数量的链式调用的函数,例如。

I want to implement a function which can accept any number of chained calls, like.

add(1)(2); // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10

如果按照以下方式实施,它只接受 1st call。

If I implement it like following, it will only accept 1st call.

function add(n){
  return function add_impl(a)
  {
   return n + a;
  };
}

我需要像下面这样写它来获得接受第二次呼叫。

And I need to write it like following to get 2nd call accepted.

function add(n){
  return function add_impl(a)
  {
   return function add_impl2(b)
   {
     return n + a + b;
   }
  }
}

我想让这个通用,这样就可以传递任意数量的参数。

I want to make this generic, so that any number of arguments can be passed.

推荐答案

你可以这样做,但你仍然需要一个空的()最后让函数知道你的计算完成了。

You could do this but you'd still need an empty () at the end to let the function know that your calculations are done.

var a = 0;
function add(n) {
  if (arguments.length) {
    a += n;
    return add;
  }
  return a;
}

var x = add(2)(3)(4)(5);
console.log(x());

这篇关于函数接受可变数量的链式调用,如`add(1)(2)(3)(4)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆