猿问

我在使用 setInterval 时遇到问题

最近几天我一直在研究这个,它看起来很简单,但我无法让它正常工作。我试图每 10 秒显示一个关于兔子的事实。我已经编写了数组、循环和函数,但它只显示数组中的最后一项。


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() {


    for (i = 0; i < bunnyArr.length; i++) {

        document.getElementById('listItem1').textContent = bunnyArr[i]

    }


}

setInterval(bunnyStat, 10000);

它也没有给我任何错误,所以我不知所措。


慕无忌1623718
浏览 157回答 3
3回答

MMTTMM

您的函数一次遍历所有数组,这就是为什么您只看到最后一个。在函数外保留一个计数器并在每次调用时增加它: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() {&nbsp; &nbsp; if (index == total) {&nbsp; &nbsp; &nbsp; &nbsp; index = 0;&nbsp; &nbsp; }&nbsp; &nbsp; document.getElementById('listItem1').textContent = bunnyArr[index++];}setInterval(bunnyStat, 10000);<div id="listItem1"></div>

慕的地10843

其他人给出了正确的答案。作为奖励,我随机化了数组,而不是在同一序列上循环。&nbsp; var lastBunnyStat = 0;&nbsp; var bunnyArr = [&nbsp; &nbsp; "Rabbits don't eat root vegetables, such as carrots",&nbsp; &nbsp; "Baby rabbits are called kittens",&nbsp; &nbsp; "A group of rabbits are called a fluffel",&nbsp; &nbsp; "Rabbits can turn their ears 180 degrees",&nbsp; &nbsp; "Their ears can pinpoint the exact location of a sound",&nbsp; &nbsp; "Rabbits don’t make good pals."&nbsp; ];&nbsp; bunnyArr.sort(function() {&nbsp; &nbsp; &nbsp; &nbsp; return 0.5 - Math.random();&nbsp; });&nbsp; // console.log(bunnyArr);&nbsp; function bunnyStat() {&nbsp; &nbsp; document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];&nbsp; &nbsp; if (lastBunnyStat >= bunnyArr.length) {&nbsp; &nbsp; &nbsp; lastBunnyStat = 0;&nbsp; &nbsp; &nbsp; bunnyArr.sort(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0.5 - Math.random();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; // console.log('endofloop');console.log(bunnyArr);&nbsp; &nbsp; }&nbsp; }&nbsp; setInterval(bunnyStat, 1200);//change to 10000

繁星点点滴滴

这是因为bunnyStat()它非常快速地循环遍历数组的所有三个元素,并在最后一个元素上结束。试试这样的:var lastBunnyStat = 0;var bunnyArr = [&nbsp; "Rabbits don't eat root vegetables, such as carrots",&nbsp; "baby rabbits are called kittens",&nbsp; "A group of rabbits are called a fluffel"];function bunnyStat() {&nbsp; document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];&nbsp; if (lastBunnyStat >= bunnyArr.length) {&nbsp; &nbsp; lastBunnyStat = 0;&nbsp; }}setInterval(bunnyStat, 10000);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答