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

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

问题描述

编写一个函数,该函数接受输入字符,并使用递归将其重复返回5次.例如,如果输入为"g",则输出应为"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.要解决该问题,请传递字符串或长度:

  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"

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

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


注意:上面的函数不会返回5次重复.那就是您的一项练习:)

如果我们把任务搁在一边,您仍然可以做"g".repeat(5) ...


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

²:多数民众赞成在打个电话.如果将递归调用放在最后一行并将其返回,引擎可以将递归优化到循环中,这会更快 且不会达到最大调用堆栈大小(无限递归仍然很糟糕) ,请尽量避免进入其中.例如,newStr.length === 5是危险的,因为长度为6的字符串将永远运行.因此,我建议使用>=<=(如上所述).

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'.

I tried the code below:

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'

My code returns: RangeError: Maximum call stack size exceeded

What am I doing wrong?

解决方案

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]); // ²
 }


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

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


¹: 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.

²: 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天全站免登陆