Javascript 索引变量
Javascript index variable
处理索引变量以递增数组值。我认为我的概念是正确的,但有一些东西,我认为在语法中,这是阻止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.
};
相关文章:
- 在索引.html和应用.js [node.js] 之间共享变量
- 传递给 PHP 表单时 JavaScript 动态变量上的未定义索引
- 如何在循环期间访问 jquery getJson 调用 ($.getJson) 中的索引变量
- 如何将索引分配给 FOR 循环中的变量名称
- 循环索引变量的节点 JS 丢失
- React:使用索引变量更新嵌套集合
- 如何在javascript中使用int变量来访问索引处的数组
- 尝试使用AJAX将JavaScript变量传递给PHP,但得到'未定义的索引'
- 如何在Javascript中使用变量作为索引从JSON数组中获取特定值
- Javascript i(index,iterator):如果用作变量,它将始终被解释为索引位置
- 将用户输入分配给索引中带有变量的对象
- Javascript 索引变量
- 通过从不同的控制器$scopes将索引推送到不同的变量中
- 未定义索引:通过AJAX传递的PHP变量
- JavaScript 数组操作,使任何索引作为变量来获取值
- 将谷歌索引内容声明在一个内联的javascript变量中
- Javascript/jQuery - 基于<选项>的变量索引制作数组
- 在变量索引处插入字符串
- 创建按变量索引的多维数组
- 通过变量索引更新mongoDB文档中的数组