【问题标题】:JavaScript: Create Function that Returns Function in which Returned Function Invokes Passed FunctionJavaScript:创建返回函数的函数,其中返回的函数调用传递的函数
【发布时间】:2019-07-12 21:45:10
【问题描述】:

我正在尝试创建一个“三次”返回另一个函数的函数。

我有以下代码:

const thrice = (inputFunc) => {
  return inputFunc()
}

let eight;

eight = thrice(() => {
  return 8;
});

const value = eight();
value

我的期望是该值等于:8。根据我的测试规范,它应该等于 8。

但是当我运行我的代码时,它会返回:TypeError: eight is not a function

我做错了什么?我的预感是我应该在三次函数中执行return inputFunc。但我从概念上不明白为什么。

【问题讨论】:

  • const thrice = f => x => f(f(f(x))) 会将函数f 应用于x 三次......我猜你需要更接近的东西。即const add1 = x => x + 1; const add3 = thrice(add1); add3(10); // =>13.
  • 您的主要问题是您正在调用thrice 中的函数,而不仅仅是返回它。更改为return inputFunc,它将按预期工作。
  • @Mark:我想我明白了;当我应该只返回以后可以调用的完整函数时,我在里面调用了三次函数
  • @PineNuts0 或者,return x => inputFunc(x)
  • 只声明了两个函数 (=>),但您调用了三个函数 (())。您删除哪个调用无关紧要,您也可以添加一个函数,但这取决于您的用例。

标签: javascript function callback iterator higher-order-functions


【解决方案1】:

注意

thrice(() => {
  return 8;
});

不是函数而是函数调用,所以eight 等于 8。 所以要解决这个问题:

eight = ()=> thrice(() => {
  return 8;
});
// or

eight =function(){ thrice(() => {
  return 8;
});};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多