Javascript Next, Prev, Random from an array

Javascript Next, Prev, Random from an array

本文关键字:an array from Prev Next Javascript Random      更新时间:2023-09-26

我创建了一个数组,当你点击随机单词按钮时选择一个随机单词,但我坚持创建下一个和上一个,以便逐步通过列表。

<Script>
        window.onload = myFunction;
        var WordList = ["a", "b", "c", "d"];
        var Word
        function myFunction() {
        var Word = WordList[Math.floor(Math.random()*WordList.length)];
        document.getElementById("Word").innerHTML = Word;
        }
        function NextWord() {
        var a = WordList.indexOf("Word");
        document.getElementById("Word").innerHTML = a;
    </script>

你的nextWord()函数没有右括号,你正在寻找字符串"Word"的索引,你更想看看变量Word的索引,像这样

    function NextWord() {
      var a = WordList.indexOf(Word) ;
      /// check if last entry 
      if((a + 1) == WordList.length) {
         /// reset
         a = 0;
      }else {
         /// increment
         a += 1;
      }
      /// set innerhtml
      document.getElementById("Word").innerHTML = WordList[a];
    }

与您可以为PreviousWord()

做的相同

缓存数组的当前索引

var currentIndex = 0, wordList = ["a", "b", "c", "d"];
function randomWord() {
  currentIndex = Math.floor(Math.random() * wordList.length);
  return wordList[currentIndex];
}
function nextWord() {
  currentIndex += 1;
  currentIndex = Math.min(currentIndex, wordList.length - 1);
  return wordList[currentIndex];
}
function prevWord() {
  currentIndex -= 1;
  currentIndex = Math.max(currentIndex, 0);
  return wordList[currentIndex];
}