我试图每秒改变身体的背景颜色,但它不起作用.我做错了什么?
var colors = [
"red", "blue", "green", "yellow", "red"
],
rand = Math.ceil(Math.random() * colors.length - 1),
t = setInterval(function() {
document.body.style.backgroundColor = colors[rand];
}, 1000);
Run Code Online (Sandbox Code Playgroud)
cwa*_*ole 10
您只需定义rand一次值,然后每次重复使用它.你的意思是:
var colors = [
"red", "blue", "green", "yellow", "red"
];
t = setInterval(function() {
// use floor instead of ceil and then you can skip the -1
var rand = Math.floor(Math.random() * colors.length)
document.body.style.backgroundColor = colors[rand];
}, 1000);
Run Code Online (Sandbox Code Playgroud)
此外,你使用逗号来分隔命令,虽然这并不总是会破坏(我至少可以想到它不会出现的情况),这通常是一个坏主意,因为它意味着有一些更大的结构继续
根据patrick dw评论,你使用逗号是正确的.它导致我在这种情况下有一种精神错乱,尤其是在rand被转移到其setInterval功能中时.我建议你可能想重写一下,var colors, t; colors =以帮助人们了解更多(有一点看起来我不是唯一一个犯这个错误的人)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |