对于循环和数组

For loop and arrays

本文关键字:数组 循环 于循环      更新时间:2023-09-26

我正在练习课程工作,想制作一个简单的代码来循环遍历数组中的每个字符串。然而,实际发生的是,它反复显示数组中的每个字符串,而不是用一种颜色替换另一种颜色。我该怎么做?

<!DOCTYPE html>
<html>
    <head>
        <title>Arrays</title>
        <script>
            colours = [" Purple"," Blue"," Pink"," Red"," Green"];
            function change() {
                for (i = 0; i < colours.length; i++) {
                    document.getElementById("hai").innerHTML += colours[i];
                }
            }
        </script>
    </head>
    <body>
        <p>The colour is: <span id=hai></span></p>
        <button id="btn" onclick="change()">Change!</button>
    </body>
    </html>

colours = [" Purple", " Blue", " Pink", " Red", " Green"];
function change() {
    for (i = 0; i < colours.length; i++) {
        document.getElementById("hai").innerHTML += colours[i];
    }
}
<p>The colour is: <span id=hai></span></p>
<button id="btn" onclick="change()">Change!</button>

这是因为附加节点的innerHTML,而不是简单地设置它,就像这样:

document.getElementById("hai").innerHTML = colours[i];

然而,我怀疑这仍然不是你想要的——我猜你每次点击后都想要一个新的颜色,在这种情况下,代码应该看起来像:

var colours = [" Purple"," Blue"," Pink"," Red"," Green"];
var currentColourIndex = 0;
function change() {
    document.getElementById("hai").innerHTML = colours[++currentColourIndex % colours.length];
}

编辑:JSFiddle示例

您需要一个索引,在change函数之外声明和初始化:

var actualIndex = 0,
    colours = [" Purple", " Blue", " Pink", " Red", " Green"];
function change() {
    actualIndex++;                 // increment
    actualIndex %= colours.length; // correct the range
    document.getElementById("hai").innerHTML = colours[actualIndex];
}
<p>The colour is: <span id="hai"></span></p>
<button id="btn" onclick="change()">Change!</button>

在这种情况下,您不需要for循环:您希望一次只显示一种颜色。

var colours = [" Purple", " Blue", " Pink", " Red", " Green"];
var currentIndex = 0;
function change() {
  if(currentIndex >= colours.length) currentIndex = 0;
  document.getElementById("hai").innerHTML = colours[currentIndex++];
}
<p>The colour is: <span id=hai></span></p>
<button id="btn" onclick="change()">Change!</button>

For循环不能用于您的需求。使用下面的代码段。

    <script>
        colours = [" Purple"," Blue"," Pink"," Red"," Green"];
        var count=0;
        function change() {
        if(count==5){
            count=0;
        }
        document.getElementById("hai").innerHTML = colours[count];
        count++;
        }
    </script>