Javascript 索引变量

Javascript index variable

本文关键字:变量 索引 Javascript      更新时间:2023-09-26

处理索引变量以递增数组值。我认为我的概念是正确的,但有一些东西,我认为在语法中,这是阻止JavaScript工作。

<html>
<head>
<style type="text/css">
 body {font-family: arial;}
 </style>
<script type="text/javascript">
function ChangeIt()
{
var colors;
colors = new Array("red", "blue", "green", "yellow", "purple");
i=0;
document.body.style.backgroundColor = colors[0];
var t = setInterval(function() {
    i=(i>=color.length) ? 0 : i+1;
    document.body.style.backgroundColor = colors[i];
}, 3000);
}
</script>
</head>
<body>
This page begins with a red background and
changes the body background to four other colors
after three seconds.<br />
The Javascript
function is set in header section and called
from the body.
</body>
<script type="text/javascript">
ChangeIt();
</script>
</body>
</html>

它很简单,在设置 i 值时,您使用的是颜色而不是颜色使用,

 i=(i>=colors.length) ? 0 : i+1;

现在工作正常,刚刚检查

将 color.length 替换为 colors.length

你忘记了"s"

var t = setInterval(function() {
    i=(i>=color.length) ? 0 : i+1;
    document.body.style.backgroundColor = colors[i];
}, 3000);
}

只是改变

i=(i>=color.length) ? 0 : i+1;

进入这个

i=(i>=colors.length) ? 0 : i+1;

.

如果您检查珍贵的浏览器控制台,您将看到:

捕获的引用错误:未定义颜色

这是因为您使用的是color而不是colors

法典:

function ChangeIt() {
    var colors;
    colors = new Array("red", "blue", "green", "yellow", "purple");
    i = 0;
    document.body.style.backgroundColor = colors[0];
    var t = setInterval(function () {
        i = (i >= colors.length) ? 0 : i + 1;
        document.body.style.backgroundColor = colors[i];
    }, 3000);
}

演示:http://jsfiddle.net/IrvinDominin/wDC9r/

主要错误可能是你引用color.length,而你的意思肯定是colors.length

但是,关于代码的许多其他事情可以改进。

  • 在声明数组时将数组分配给colors
  • 您可以使用数组文本代替 new Array()
  • 在一行中声明变量,使变量i ChangeIt()局部,但仍可用于区间函数的范围。
  • 将"增量i"行更改为更易于阅读的内容(例如,在三元语句中将0赋值为"else")。

以下是更改:

function ChangeIt() {
     var colors = ["red", "blue", "green", "yellow", "purple"], 
         i = 0,  
         fn = function() {
             i = (i < colors.length) ? i + 1 : 0;
             document.body.style.backgroundColor = colors[i];
         },
         t = setInterval(fn, 3000);
     fn(); // To set the background immediately.
};