Javascript 如何递归重写此函数?
在这种情况下,有没有一种方法可以使用递归替换for循环?我想把99瓶熊装在墙上的歌打印出来。我一直在努力,但无法使它发挥作用。我是否需要重写代码以便可以递归重写Javascript 如何递归重写此函数?,javascript,recursion,Javascript,Recursion,在这种情况下,有没有一种方法可以使用递归替换for循环?我想把99瓶熊装在墙上的歌打印出来。我一直在努力,但无法使它发挥作用。我是否需要重写代码以便可以递归重写 { function main() { input = Number(prompt("How many bottles do you have?")); for (let i=input; i > 0; --i){ if (i == 1){
{
function main() {
input = Number(prompt("How many bottles do you have?"));
for (let i=input; i > 0; --i){
if (i == 1){
console.log(i, "bottles of beer on the wall", i, "bottles of beer.");
console.log("Take one down and pass it around, no more bottles of bear on the wall");
console.log("No more bottles of bear on the wall, no more bottles of beer.");
i = input;
console.log("Go the store and buy some more,", i, "bottles of beer on the wall.")
break;
}else {
console.log(i, "bottles of beer on the wall", i, "bottles of beer.");
console.log("Take one down and pass it around,",i-1, "bottles of bear on the wall");
}
}
}
main();
}
我会用下面的方法来做:
主功能(输入,原始){
如果(!输入){
输入=数字(提示(“您有多少瓶?”);
}
如果(!原件){
原始=输入;
}
如果(输入=1){
log(`${input}瓶啤酒挂在墙上${input}瓶啤酒。`);
console.log(‘取下一瓶并传给周围,墙上不再有熊瓶子’);
console.log('墙上不再有啤酒瓶,不再有啤酒瓶');
log(`去商店,在墙上再买几瓶${original}瓶啤酒。`);
}否则{
log(`${input}瓶啤酒挂在墙上${input}瓶啤酒。`);
log(`Take one down and pass it,${input-1}瓶啤酒挂在墙上`);
}
如果(输入>1){
主(输入-1,原件);
}
}
main()代码>是的,可以用递归替换循环。您能告诉我们您的尝试,以便我们看到您的错误所在吗?这缺少i=input
使原始的循环成为无限循环。不确定你的意思是什么?哦,对不起,我错过了原始代码中的break
语句,并且认为该代码旨在生成无限版本的歌曲文本-它不应该。但是,您的版本仍然无法在outputOh nice find的最后一行中打印原始输入的号码(“去商店,再多走几步;墙上挂着99瓶啤酒”)。我现在会解决的。编辑,我不知道这首歌,所以我在这里不发表你的评论;)