【问题标题】:JavaScript: Accept Division Function as Argument Into Another Function That Returns New Function --> Returns QuotientJavaScript:接受除法函数作为返回新函数的另一个函数的参数->返回商
【发布时间】:2019-10-11 06:32:48
【问题描述】:

我有一个分割两个输入参数的函数:

const divide = (x, y) => {
    return x / y;
  };

我有第二个函数,它将除法函数作为其输入参数并返回一个新函数。

function test(func) {

    return function(){
        return func(); 
    }
}

const retFunction = test(divide);
retFunction(24, 3)

我希望返回的值为 8 (24 / 3)。但我得到了“NaN”的返回输出。我究竟做错了什么?

【问题讨论】:

    标签: javascript callback return closures higher-order-functions


    【解决方案1】:

    您需要将可能的参数传递给函数:...args:

    const divide = (x, y) => {
      return x / y;
    };
    
    function test(func) {
      return function(...args) {
        return func(...args);
      }
    }
    
    const retFunction = test(divide);
    const result = retFunction(24, 3);
    console.log(result);

    【讨论】:

    • 值得注意的是,如果你不在 es6 兼容的环境中,.apply 是你所做的,而不是 (...args) 所以你会做 return func.apply(null, arguments); 而不是 return func(...args);跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2015-04-11
    相关资源
    最近更新 更多