Javascript递归示例麻烦

时间:2017-10-29 08:45:21

标签: javascript recursion

const writeText = function(word, n) {
  if(n >= 5) {
    return '';
  }
  n = n + 1;
  return word + writeText(word + n);
};

debugger;

writeText('hello', 1);

我想编写一个代码,它将使用递归返回'hello1','hello2',...'hello5'。 我的代码不起作用所以我使用调试器来查看错误。它表明在第一次递归调用后, n 变为 undefined 。任何人都可以帮我解决这个代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

一些提示:

  • 使用递归调用时,最好使用命名函数而不是函数表达式,因为名称不随函数的赋值而改变。这对于递归调用是必要的,这可能会调用未知函数。

  • 如果值大于5,则退出功能。

  • 您需要显示n的实际值(也许是新行)。

  • 使用单词和递增值的第二个参数调用函数。



function writeText(word, n) {
    if (n > 5) {
        return '';
    }
    return word + n + '\n' + writeText(word, n + 1);
};

console.log(writeText('hello', 1));




答案 1 :(得分:0)

你几乎就在那里 - @Nina Scholz提供的答案很好。

这是一种可以使用ES6模板文字来使我们保持最新的方法。

由于您对谷歌的语法提出了一些新的评论:

=> : arrow functions `text` : template literals



const writeText = (word, n) => 
  `${word+n} ${n < 5 ? writeText(word, n+1) : ''}`;
 
console.log(writeText('hello',1))
&#13;
&#13;
&#13;

```