Javascript 对于循环和数组
我正在练习课程作业,想编写一个简单的代码,循环遍历数组中的每个字符串。然而,实际情况是,它会反复显示数组中的每个字符串,而不是用一种颜色替换另一种颜色。我该怎么做Javascript 对于循环和数组,javascript,html,arrays,for-loop,Javascript,Html,Arrays,For Loop,我正在练习课程作业,想编写一个简单的代码,循环遍历数组中的每个字符串。然而,实际情况是,它会反复显示数组中的每个字符串,而不是用一种颜色替换另一种颜色。我该怎么做 <!DOCTYPE html> <html> <head> <title>Arrays</title> <script> colours = [" Purple"," Blue"," Pink","
<!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>
阵列
颜色=[“紫色”、“蓝色”、“粉色”、“红色”、“绿色”];
函数更改(){
对于(i=0;i
改变
colors=[“紫色”、“蓝色”、“粉色”、“红色”、“绿色”];
函数更改(){
对于(i=0;i
颜色为:
改变代码>这是因为您要附加节点的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];
}
编辑:您需要一个索引,在change函数之外声明和初始化:
var现实指数=0,
颜色=[“紫色”、“蓝色”、“粉色”、“红色”、“绿色”];
函数更改(){
实现索引+++;//增量
实施索引%=colors.length;//更正范围
document.getElementById(“hai”).innerHTML=colors[actualIndex];
}
颜色为:
改变代码>在这种情况下,您不需要for循环:您希望一次只显示一种颜色
var colors=[“紫色”、“蓝色”、“粉色”、“红色”、“绿色”];
var currentIndex=0;
函数更改(){
如果(currentIndex>=colors.length)currentIndex=0;
document.getElementById(“hai”).innerHTML=colors[currentIndex++];
}
颜色为:
改变循环代码>不能用于您的要求。使用下面的代码片段
<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>
颜色=[“紫色”、“蓝色”、“粉色”、“红色”、“绿色”];
var计数=0;
函数更改(){
如果(计数=5){
计数=0;
}
document.getElementById(“hai”).innerHTML=colors[count];
计数++;
}
这里有一个提示。使用包含数组中当前显示的元素的索引的变量。在change
函数中,增加该指针(记住在数组末尾使其返回到0),并显示相应的数组值,可能与模数相同。我从来没有想过。好好利用假账户下一次更好地解释你需要什么。即使回答了你的问题,我的票数也会下降。这和托马斯的答案完全一样。不完全一样,我把指数保持在较低的水平,另一个答案会不断增加,直到它永远不会消失。