【问题标题】:Passing a function as a parameter in javascript and not as the function's returned value在javascript中将函数作为参数而不是作为函数的返回值传递
【发布时间】:2018-02-03 21:51:30
【问题描述】:

假设我有一个随机返回值 1-6 的函数 roll()。现在,如果我有另一个名为 repeatFunction 的函数,它接受一个函数作为参数和一个数字 n。 repeatFunction 的目的是调用它作为参数 n 次的任何函数。但是,如果我将 roll() 作为参数传递,repeatFunction 会将其解释为 roll() 函数返回的值 1-6,而不是函数。我目前的代码如下:

function repeatFunction(func, n){
    for(i = 0; i < n; i++){
        func;
    }
}
repeatFunction(roll(), 10);

如何获得它,以便 repeatFunction 将 func 参数解释为函数而不是返回值,以便我可以在 repeatFunction 中再次调用它?

【问题讨论】:

    标签: javascript function parameters callback


    【解决方案1】:

    传递对roll 函数的引用并在repeat 函数中作为回调调用它。像这样,

    function repeatFunction(func, n){
        for(i = 0; i < n; i++){
            func();
        }
    }
    repeatFunction(roll, 10);
    

    【讨论】:

      【解决方案2】:

      你需要传递函数名而不是返回的执行。

      您正在执行函数roll,只需传递roll

      repeatFunction(roll(), 10);
                     ^
      

      看这段代码sn-p

      重复的函数会递归执行函数fn,直到i == n

      function repeatFunction(fn, n, i){
          if (i === n) return;
          fn();
          
          repeatFunction(fn, 10, ++i);
      }
      
      var roll = function() {
        console.log('Called!');
      };
      
      repeatFunction(roll, 10, 0);
      .as-console-wrapper {
        max-height: 100% !important
      }
      看?该函数被称为n 次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多