colors = new           Array("red","orange","blue","purple","yellow","brown","green","grey")

var colorIndex = 0;
function changeColor(){
document.body.bgColor=colors[colorIndex]
 colorIndex = (colorIndex+1)%8)


}

 function startColorChange(){

 setInterval("changeColor()",1000)
}
window.onload = startColorChange
console.log(colors.length);


其代码每隔1秒钟重复更改文档背景颜色。
  变量colorIndex每次都会增加,并通过更改不同的颜色来显示输出。但是问题iscolorIndex =(colorIndex + 1)%8。第一次,它的值为0,所以将显示红色,但在下一轮中,它的意志值将变为0.125,然后橙色如何显示,即使其索引明显为1而不是0.125,同样,每次索引都不从0增加到1时, 2,3,4,5 ...然后分别改变颜色。

最佳答案

如果删除最后的括号,则代码工作正常:

colorIndex = (colorIndex+1)%8)
//                          ^^^


较低的建议具有更清晰的代码。



var colors = ["red", "orange", "blue", "purple", "yellow", "brown", "green", "grey"],
    colorIndex = 0;

function changeColor() {
    document.body.bgColor = colors[colorIndex];
    colorIndex = (colorIndex + 1) % colors.length;
}

function startColorChange() {
    setInterval(changeColor, 1000);
}

window.onload = startColorChange;

09-25 18:42