如何在Javascript中实现这种链接

如何在Javascript中实现这种链接

This question already has an answer here:
Writing a function f which would satisfy the following test
                                
                                    (1个答案)
                                
                        
                在10个月前关闭。
            
        

f()()('x') // foox

f()()()()('x') //foooox

我试图返回嵌套函数,但无法获得期望的结果。

最佳答案

如果未定义变量,只需使用计数器变量并返回一个函数。



const f = (a, c = 0) => a ? "f" + "o".repeat(c) + a : b => f(b, ++c);
console.log(f()()("x"));
console.log(f()()()()("z"));





ES5语法:



function f(a, c) {
  c = c || 0;
  if (a) {
    return "f" + "o".repeat(c) + a;
  } else {
    return function(b) {
      return f(b, c + 1);
    }
  }
}
console.log(f()()("x"));
console.log(f()()()()("z"));

关于javascript - 如何在Javascript中实现这种链接? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56644875/

10-11 13:12