dI正在尝试使用for循环来展示儿童歌曲“墙上挂着10个绿色瓶子”。所以我从10开始循环,一直到0。文本应该是累加的,最后应该显示整个歌曲
for 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发布于 2019-09-20 03:14:27
更新你的for循环输入错误,用i--代替tall。
另一个问题是在双引号中使用"poem"和"poem1 ",这意味着它是一个字符串,因此歌曲和诗歌的实际值不会在for循环中使用。
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();<div id="demo"></div>
发布于 2019-09-20 03:19:17
显示不带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>https://stackoverflow.com/questions/58017478
复制相似问题