Home > Web Front-end > JS Tutorial > JavaScript randomly selects 10 non-repeating numbers between 0-100_javascript skills

JavaScript randomly selects 10 non-repeating numbers between 0-100_javascript skills

PHP中文网
Release: 2016-05-16 15:13:36
Original
2686 people have browsed it

Currently, I have only learned two simple methods to help you randomly select 10 non-repeating numbers between 0-100. The details are as follows

The first method Use the feature that the array length can be rewritten

Idea: You can use a for loop to loop out the numbers from 0 to 100 and put them in an array, and then use sort( ) randomly scrambled, and then by rewriting the length of this array to 10, 10 different numbers were obtained.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
  var arr=[];
  for(var i=0;i<100;i++){//一个从0到100的数组
    arr.push(i);
  }
  arr.sort(function(){//随机打乱这个数组
    return Math.random()-0.5;
  })
  arr.length=10;//改写长度
  console.log(arr);//控制台会输出10个不同的数
  </script>
</head>
<body>
</body>
</html>
Copy after login

The second one takes advantage of the unique key value of the json object.

Idea: first define an empty array to save the array and an empty json object,

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
  //json对象,key值是唯一的,key值可以为数字
  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>
Copy after login

The above is the content of JavaScript techniques for randomly selecting 10 non-repeating numbers between 0-100. For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template