J'ai réussi à parcourir le tableau alphabétique mais dans un ordre aléatoire lorsque je clique sur le bouton de défilement. Comment puis-je parcourir le tableau mais dans le bon ordre et quand il atteint Z pour recommencer au début sans s'arrêter.

function roll() {
  var alphabet = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ];

  setInterval(function () {
    for (i = 0; i < alphabet.length; i++) {
      document.querySelector("span").innerHTML =
        alphabet[Math.floor(Math.random() * alphabet.length)];
    }
  }, 800);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="main">
      <span></span>
      <button id="roll" onclick="roll()">roll</button>
    </div>
    <script src="main.js"></script>
  </body>
</html>
0
Nick 15 nov. 2020 à 20:36

1 réponse

Meilleure réponse
  function roll() {
      var i=0;
      var alphabet = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ];
    
      setInterval(function () {
        if (i == alphabet.length){
          i=0;   
        }
        document.querySelector("span").innerHTML =  alphabet[i];
        i++;        
      }, 800);
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>Document</title>
      </head>
      <body>
        <div class="main">
          <span></span>
          <button id="roll" onclick="roll()">roll</button>
        </div>
        <script src="main.js"></script>
      </body>
    </html>
1
Yuva Raja 15 nov. 2020 à 17:51