javascript randomly selects 10 numbers that are not repeated between 0 and 100

  • 2021-01-11 01:50:56
  • OfStack

So far, I have only learned two simple methods to help you randomly select 10 numbers that are not repeated between 0 and 100. The details are as follows

The first takes advantage of the feature that the array length can be overwritten

You can loop out the numbers from 0 to 100 using for and put them into an array. Then you can randomly scramble the 100 numbers using sort(). Then you can rewrite the array's length to 10 to get 10 different numbers.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
  var arr=[];
  for(var i=0;i<100;i++){//1 A from 0 to 100 An array of 
    arr.push(i);
  }
  arr.sort(function(){// Randomly shuffle this array 
    return Math.random()-0.5;
  })
  arr.length=10;// Rewrite the length 
  console.log(arr);// The console will print 10 I have three different numbers 
  </script>
</head>
<body>
</body>
</html>

The second takes advantage of the fact that the key value of the json object is only 1.

An empty array and an empty json object are defined, respectively.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
  //json object ,key Value is only 1 the ,key The value can be a number 
  var arr=[];
  var json={};
  while(arr.length<10){
    var k=Math.round(Math.random()*100);
    if(!json[k]){
      json[k]=true;
      arr.push(k);
    }
  }
  console.log(arr)
  </script>
</head>
<body>
  
</body>
</html>

I hope this article will help you learn javascript program design.


Related articles: