简体   繁体   中英

How to generate non-recurring numbers from the range JavaScript

I have array with 10 items, I calls one random item using a random number from 1 to 10, what to use to make a random number from 1 to 10, which will not happen again, and when all 10 is used, the program stops randomly? code

const num = () => Math.floor(Math.random() * 10);
  const postWord = () => {
    randomWord = word.innerText = words[num()].PL;
  }

  postWord();

  submit.addEventListener("click", function() {
    postWord();
  });

Have you ever considered to move the array items?

var range = 10; // global variable

const num = () => Math.floor(Math.random() * range);
  const postWord = () => {
    randomWord = word.innerText = words[num()].PL;
    for (var i=num(); i < range; i++) {
        var temp = words[i];
        words[i] = words[i+1];
        words[i+1] = temp;
    }
    range--;
  }

  postWord();

  submit.addEventListener("click", function() {
    if (range) {
      postWord();
    }
  });

I am not that familiar with JS but I guess my code can at least demonstrate my point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM