3 回答
TA贡献1869条经验 获得超4个赞
您的函数一次遍历所有数组,这就是为什么您只看到最后一个。
在函数外保留一个计数器并在每次调用时增加它:
var bunnyArr = ["Rabbits don't eat root vegetables, such as carrots", "baby rabbits are called kittens", "A group of rabbits are called a fluffel"];
var index = 0;
var total = bunnyArr.length;
function bunnyStat() {
if (index == total) {
index = 0;
}
document.getElementById('listItem1').textContent = bunnyArr[index++];
}
setInterval(bunnyStat, 10000);
<div id="listItem1"></div>
TA贡献1785条经验 获得超8个赞
其他人给出了正确的答案。作为奖励,我随机化了数组,而不是在同一序列上循环。
var lastBunnyStat = 0;
var bunnyArr = [
"Rabbits don't eat root vegetables, such as carrots",
"Baby rabbits are called kittens",
"A group of rabbits are called a fluffel",
"Rabbits can turn their ears 180 degrees",
"Their ears can pinpoint the exact location of a sound",
"Rabbits don’t make good pals."
];
bunnyArr.sort(function() {
return 0.5 - Math.random();
});
// console.log(bunnyArr);
function bunnyStat() {
document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];
if (lastBunnyStat >= bunnyArr.length) {
lastBunnyStat = 0;
bunnyArr.sort(function() {
return 0.5 - Math.random();
});
// console.log('endofloop');console.log(bunnyArr);
}
}
setInterval(bunnyStat, 1200);//change to 10000
TA贡献1803条经验 获得超3个赞
这是因为bunnyStat()它非常快速地循环遍历数组的所有三个元素,并在最后一个元素上结束。试试这样的:
var lastBunnyStat = 0;
var bunnyArr = [
"Rabbits don't eat root vegetables, such as carrots",
"baby rabbits are called kittens",
"A group of rabbits are called a fluffel"
];
function bunnyStat() {
document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];
if (lastBunnyStat >= bunnyArr.length) {
lastBunnyStat = 0;
}
}
setInterval(bunnyStat, 10000);
添加回答
举报