亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我在使用 setInterval 時遇到問題

我在使用 setInterval 時遇到問題

慕無忌1623718 2021-06-30 17:33:46
最近幾天我一直在研究這個,它看起來很簡單,但我無法讓它正常工作。我試圖每 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);它也沒有給我任何錯誤,所以我不知所措。
查看完整描述

3 回答

?
MMTTMM

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>


查看完整回答
反對 回復 2021-07-01
?
慕的地10843

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


查看完整回答
反對 回復 2021-07-01
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

這是因為bunnyStat()它非??焖俚匮h遍歷數組的所有三個元素,并在最后一個元素上結束。試試這樣的:


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);


查看完整回答
反對 回復 2021-07-01
  • 3 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號