问题希望我输出字符串“Edabit”,其中“a”字符的数量等于通过函数传递的初始数量。
我尝试了不同的连接方法,但由于某种原因,“a”字符串似乎忽略了它们在连接中的位置。
function howManyTimes(num) {
let str = ''
if (num === 0){
return `Ed${str}bit`
}
else {
str += 'a'
return str += howManyTimes(num - 1)
}
}
console.assert(howManyTimes(0) == "Edbit", "1. Instead got "+howManyTimes(0));
console.assert(howManyTimes(1) == "Edabit", "2. Instead got "+howManyTimes(1));
console.assert(howManyTimes(10) == "Edaaaaaaaaaabit", "3. Instead got "+howManyTimes(10));
最佳答案
function howManyTimes(num, str) {
if (!str) str = '';
if (num > 0) {
return howManyTimes(num - 1, str + 'a');
} else {
return `Ed${str}bit`;
}
}
console.log(howManyTimes(8));
一个问题是您的递归始终将方法的结果附加到 a
中。不要这样做,而是传递聚合的字符串,然后在到达末尾时使用。
关于javascript - 递归挑战 - Edabit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63587210/