简体   繁体   English

在JavaScript中将递归函数转换为箭头函数

[英]converting recursive function to arrow function in javascript

How can i convert following function to arrow function? 如何将以下功能转换为箭头功能? I am using currying here 我在这里用咖喱粉

function mergeString(str){
   return function(str1){
     if(str1){
        return mergeString(str + ' ' + str1); 
     }
     else
     {
       return str;
     }
   }
}

You could chain the function heads and then the function body for all. 您可以先链接功能头,然后再链接所有功能体。

 const mergeString = str => str1 => str1 ? mergeString(str + ' ' + str1) : str; console.log(mergeString('a')()); console.log(mergeString('a')('b')('c')()); console.log(mergeString('this')('should')('work')('as')('well')()); 

Actuall this is a good usecase for rest parameters: 实际上,这是其余参数的一个很好的用例:

 const mergeStrings = (...strings) => strings.join(" ");

Usable as: 可用作:

mergeString(
  "one",
  "two",
  "three"
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM