在提出这个问题之前,我进行了非常彻底的搜索,但找不到我要找的东西。我想先说这是我用 JavaScript 编写代码的第五天,所以请放轻松!
我正在参加一个完整程序的预备编码类(class),我们的目标之一是编写一个函数 repeatString(string, count)
,它接受一个字符串和你重复的次数希望它作为参数重复。这是我的递归版本:
function repeatString(string, count) {
if ( count === 0 ) {
return "";
}
if ( count === 1 ) {
return string;
}
if ( count > 1 ) {
return string + repeatString(string, count - 1);
}
}
然后我们应该使用 while 而不是递归来重写函数。这就是我卡住的地方:
function repeatString(string, count) {
var num = 0;
if ( count === 0 ) {
return "";
}
while ( num < count ) {
num += 1;
return string;
}
}
无论计数如何,我当前的代码只返回一次字符串,除非计数为零。我确定我面前有一个明显的错误,但我的初学者眼睛没有注意到它。
最佳答案
试试这个,你需要在返回之前构建字符串。如果你不使用递归,你只返回一次:</p>
function repeatString(string, count) {
var num = 0;
var str = "";
if ( count === 0 ) {
return "";
}
while ( num < count ) {
num += 1;
str = str + string;
}
return str;
}
repeatString("asdf", 2)
"asdfasdf"
关于Javascript:使用 while 循环在给定的计数参数中重复一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221255/