ES6立即调用递归箭头函数 [英] ES6 immediately invoke recursive arrow function

查看:664
本文介绍了ES6立即调用递归箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前的代码:

const fn = parameter => {
    // if, else ...
    fn(X);
};
fn(0);

现在,我无法使用这种方法,因为我需要用参数调用函数,并且必须以递归方式调用。

Now, I can't use this approach as I need to call the function with a parameter and it must be callable recursively.

如何重构上面的箭头函数以立即调用并递归调用?

How to refactor the above arrow function to be immediately invoked and recursively callable?

推荐答案

首先,让我放一下免责声明立即调用函数表达式(IIFE)是在ES6中被认为是不好的做法,这是尾递归,我个人会把它改为for循环。

First, let me put the disclaimer that Immediately-Invoked-Function-Expressions (IIFE) are considered bad practice in ES6, and this is tail-recursion and personally I would change it to a for loop.

但是我总是可以这样做:

but you can always do this I guess:

((x) =>{ const fn=(p)=>{
       //whatever
       fn(q)
   }
   fn(x)
})(0)

这篇关于ES6立即调用递归箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆