JavaScript:编写一个函数,该函数接受一个输入字符并使用递归返回该字符重复 5 次 [英] JavaScript: Write a function that takes an input character and returns that character repeated 5 times using recursion

查看:29
本文介绍了JavaScript:编写一个函数,该函数接受一个输入字符并使用递归返回该字符重复 5 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个函数,该函数接受一个输入字符并使用递归返回该字符重复 5 次.例如,如果输入是'g',那么输出应该是'ggggg'.

Write a function that takes an input character and returns that character repeated 5 times using recursion. For example, if the input is 'g', then the output should be 'ggggg'.

我尝试了以下代码:

function repeater(char) {

  let newStr = ''; 

  if (newStr.length === 5){
    return newStr; 
  }

  else {
    newStr += char; 
  }

  return repeater(char); 
}

// To check if you've completed the challenge, uncomment these console.logs!
console.log(repeater('g')); // should return 'ggggg'
//console.log(repeater('j')); 'jjjjj'

我的代码返回:RangeError: Maximum call stack size exceeded

我做错了什么?

推荐答案

原因 newStr 是一个局部变量,不会在递归调用中传递.因此,每次调用都会创建一个新的 newStr,其长度始终为 0.要解决该问题,请传递字符串或长度:

Cause newStr is a local variable that does not get passed on in the recursive call. Therefore, a new newStr will be created on each call, and its length will always be 0. To resolve that, either pass on the string, or the length:

  function repeat(char, result = "") { 
    if(result.length / char.length >= 3) return result;
    return repeat(char, result + char); // ²
 }

 // a call goes like:
 // repeat("g", "")
 // repeat("g", "g")
 // repeat("g", "gg")
 // repeat("g", "ggg")

 // OR

 function repeat(char, count = 3) { /*¹*/
    if(count <= 1) return char;
    return char + repeat(char, count - 1);
 }

 // repeat("g", 3)
 // "g" + repeat("g", 2)
 // "g" + "g" + repeat("g", 1)
 // "g" + "g" + "g"

或者,如果这只适用于给定的一个字符(如任务所述):

Or if this should only work with one char given (as the task says):

 function repeat(char) {
   if(char.length >= 3) return char;
   return repeat(char + char[0]); // ²
 }

<小时>

注意:以上函数不会返回 5 次重复.这留给你作为练习:)


Note: The functions above won't return 5 repeats. Thats left as an exercise to you :)

如果我们把任务放在一边,你可以只做 "g".repeat(5) 不过......

If we take the assignment aside you could just do "g".repeat(5) though ...

¹:= 3 是所谓的默认参数".这意味着 repeat("g") 等于 repeat("g", 3).优点是你可以对不同的长度重复使用它,repeat("g", 10) 将重复 g 10 次.

¹: The = 3 is a so called "default argument". That means that repeat("g") equals repeat("g", 3). The advantage is that you can reuse this for different lengths, repeat("g", 10) will repeat g 10 times.

²:那是尾声.如果将递归调用放在最后一行并返回,引擎可以将递归优化为循环,这样会更快并且不会达到最大调用堆栈大小(无限递归仍然不好), 尽量避免进入它.例如 newStr.length === 5 是危险的,因为长度为 6 的字符串将永远运行.因此我建议使用 >=<=(如我上面所做的那样)).

²: Thats a tail call. If you place the recursive call at the last line and return it, the engine can optimize the recursion into a loop, which is way faster and does not reach a maximum call stack size (infinite recursion is still bad, try to always avoid getting into it. newStr.length === 5 for example is dangerous, as a string of length 6 would run forever. Therefore I'd recommend using >= or <= (as I did above)).

这篇关于JavaScript:编写一个函数,该函数接受一个输入字符并使用递归返回该字符重复 5 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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