我正在尝试使用for循环播放儿童歌曲“墙上挂着10个绿色瓶子”。因此,我从10开始循环播放,然后从0开始播放。应该将文字加起来,最后显示全部歌曲
对于i = 10 i = 0 i--,循环内的文本。数字应该在变化,但是其余的应该保持不变
<div id="demo"></div>
<script>
function favsong() {
var i;
var song = "";
var poem = "green bottles, hanging on a wall";
var poem1 ="If 1 green bottle were to accidentally fall. There'd be";
for (i=10;i=0;i--) {
song+=i+poem+"<br>"+i+poem+"<br>"+poem1;
if (i==1){
song+="1 green bottle hanging on the wall"+"<br>+"1 green bottle hanging on the wall"
continue
}
}
document.getElementById("demo").innerHTML = song;
}
</script>
10 green bottles, hanging on a wall,
10 green bottles, hanging on a wall,
If 1 green bottle were to accidentally fall
There'd be 9 green bottles, hanging on the wall
9 green bottles, hanging on a wall,
9 green bottles, hanging on a wall,
If 1 green bottle were to accidentally fall
There'd be 8 green bottles, hanging on the wall
8 green bottles, hanging on a wall,
8 green bottles, hanging on a wall,
If 1 green bottle were to accidentally fall
There'd be 7 green bottles, hanging on the wall
... and so on...
1 green bottles, hanging on a wall,
1 green bottles, hanging on a wall,
If 1 green bottle were to accidentally fall
There'd be 0 green bottles, hanging on the wall
答案 0 :(得分:0)
更新您的for循环键入错误,以使用library(dplyr)
df1 %>%
slice(tail(row_number(), 5))
代替i--
。
另一个问题是在双引号中使用tall
和"poem"
,这意味着它是一个字符串,因此在循环中不使用song和poem的实际值。
"poem1 "
function text1() {
var i= 0;
var song = "";
var poem = " green bottles, hanging on a wall";
var poem1 = "if 1 green bottle were to accidentally fall. There'd be "
for (i = 10; i > 0; i--) {
song += i + poem + "<br>" + i +"" + poem + "<br>" + poem1 + "";
document.getElementById("demo").innerHTML = song;
}
}
text1();
答案 1 :(得分:0)
显示零个没有poem1的瓶子。还使用模板文字来提高可读性。
<div id="demo"></div>
<script>
function text1() {
var i;
var song = "";
var poem = "green bottles, hanging on a wall\n";
var poem1 = "if 1 green bottle were to accidentally fall. There'd be\n"
for (i = 10; i >= 0; i--) {
song += `${i} ${poem}${i} ${poem}`
if(i) {song += poem1}
}
document.getElementById("demo").innerHTML = song;
}
</script>