对于循环和数组
For loop and arrays
我正在练习课程工作,想制作一个简单的代码来循环遍历数组中的每个字符串。然而,实际发生的是,它反复显示数组中的每个字符串,而不是用一种颜色替换另一种颜色。我该怎么做?
<!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>
相关文章:
- javascript:数组循环
- 如何将数组循环到JSON代码中
- 而与数组循环
- JavaScript 数组/循环不起作用
- AJAX在数组循环中调用,只在上一次完成后调用next
- 数组循环以获取单个值
- JavaScript数组循环
- Javascript 2D数组循环停止
- 通过Javascript中的JSON数组循环
- 为什么以下 forEach 数组循环未返回未定义
- 如何在数组循环中过滤数据
- 如何在数组循环 222 中过滤数据
- 数组循环以确定范围平均值
- 对象的数组循环
- 对象键及其值的数组循环
- 虽然的缺点!未定义的数组循环
- 数组循环导致无限循环
- 数组循环 - 处理下拉列表中的空值
- 在 Node 中连接数组循环.js glob 结果
- JavaScript 图像数组循环