javascript – 创建一个具有不确定数量的连续调用的函数

前端之家收集整理的这篇文章主要介绍了javascript – 创建一个具有不确定数量的连续调用的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作为编程挑战的一部分,我们的任务是创建一个具有不确定数量的连续调用函数.举个例子,假设函数只返回提供的参数的总和,它应该如下工作:
sum(4)() // 4
sum(4)(5)() // 9
sum(4)(5)(9)() // 18
sum(4)(5)(9)(1)() // 19
// etc...

最后允许的空函数调用简化了问题,作为调用结束的指示.

我已经开发了一个解决方案来完成工作,但在函数本身内部使用@R_502_398@:

var sum = function (a) {
    if (!sum.init) {
        sum.total = 0;
        sum.init = true;
    }
    if (!arguments.length) {
        sum.init = false;
        return sum.total;
    }
    sum.total += a;
    return sum;
};

这个解决方案有效,但使用状态,@R_502_398@和函数对象技巧,这是不理想的.我的问题是,是否有办法以纯粹的递归方式解决问题.

作为旁注,如果没有提供最后一次空调(),我不相信问题可以解决,但如果我错了请告诉我.

更新

CodeReview中已回答此问题:https://codereview.stackexchange.com/a/153999/129579

一种不依赖于全局范围且纯功能的neet解决方案.

解决方法

你可以利用闭包来实现你想要的东西:
function sum(value){
  // the closure variable that will be accessible for all the _sum calls (initialised to 0 for every sum call).
  var result = 0;
  
  // the function that will be returned (sum will only get called once to initialize the result to 0. It's _sum which will be returned as much as possible)
  function _sum(a){
    // if we passed a parameter,then add it to result and return a new _sum
    if(typeof a != "undefined"){
      result += a;
      return _sum;
    }
    // if we didn't return the result
    else
      return result;
  }
  // of course after initializing result we need to call _sum that handle the actual summing and return whatever it returns (if value is defined,it will return another `_sum` if not it will return the value of result which will be 0 at first) from now on sum will have nothing to do with the rest of the calls (()()()... )
  return _sum(value);
}

console.log("sum() = " + sum());
console.log("sum(7)() = " + sum(7)());
console.log("sum(5)(6)(7)() = " + sum(5)(6)(7)());

// will return 0 because we call sum again
console.log("sum() = " + sum());

注:总和(1)(7)(3)());将按此顺序致电:

>与参数1相加,将结果初始化为0并调用
> _sum具有相同的参数1,它将把它添加到结果并返回一个新的ins of _sum将被调用,所以以下
> _sum用参数7调用,添加它并返回一个新的_sum所以新的
> _sum用参数3调用,…生成另一个
> _sum将没有参数,因此如果(typeof a!=“undefined”)将失败并且此_sum将返回结果.

实际的总和仅在开始初始化时调用一次.正如我所说的那样,_sum会在此之后被链接到最后.

原文链接:https://www.f2er.com/js/157933.html

猜你在找的JavaScript相关文章