How to randomly generate numbers without repetition in javascript?

前端 未结 11 2386
时光取名叫无心
时光取名叫无心 2020-12-06 11:52

I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:

for(var l=0; l<5; l++)          


        
11条回答
  •  北海茫月
    2020-12-06 12:51

    So many solutions to this! Here's my code for a reuseable function that takes in 3 arguments: the number of integers wanted in the array (length) and the range that the array should be comprised of (max and min).

    function generateRandomArr(length, max, min) {
      const resultsArr = [];
      for (let i = 0; i < length; i++) {
        const newNumber = Math.floor(Math.random() * (max - min)) + min;
        resultsArr.includes(newNumber) ? length += 1 : resultsArr.push(newNumber);
      }
      return resultsArr;
    }
    
    generateRandomArr(10, 100, 0);
    // this would give a list of 10 items ranging from 0 to 100
    // for example [3, 21, 56, 12, 74, 23, 2, 89, 100, 4]
    

提交回复
热议问题