Home  >  Article  >  Web Front-end  >  JS implements random number generation for deduplication

JS implements random number generation for deduplication

php中世界最好的语言
php中世界最好的语言Original
2018-04-17 15:49:082657browse

This time I will bring you the random number generation with JS to achieve deduplication. What are the precautions for JS to realize the random number generation with deduplication. The following is a practical case, let’s take a look.

1. Preparation before experiment:

Understanding of Math functions

Understanding array methods

2. Experimental operation:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <title>随机数生成</title> 
</head> 
<style type="text/css"> 
body{font-size: 20px;} 
#box{border:3px solid #666;width:500px;height:300px;margin:20px auto;padding:20px;position: relative;} 
#min,#max{width: 60px;margin:5px;} 
#num{margin:15px;width: 115px;} 
button{width:80px;height:30px;letter-spacing: 10px;font-size: 15px;} 
h1{margin: 10px 90px;} 
</style> 
<body> 
<p> 
  <p id="box"> 
    <h1>课堂提问生成器</h1> 
    <label>产生随机数的范围:</label><input type="text" id="min">--<input type="text" id="max"></br> 
    <label>需要产生多少个随机数:</label><input type="text" id="num"></br> 
    <button onclick="produce()">生成</button> 
    <p id="result"></p> 
  </p> 
</p> 
</body> 
<script type="text/javascript"> 
  function produce(){ 
    var omin=document.getElementById("min").value; 
    var max=document.getElementById("max").value; 
    var num=document.getElementById("num").value; 
    var oArray=new Array; 
    var result=""; 
    var min=omin; 
    for(var i=0;i<=max-omin;i++){ 
       oArray[i]=min; 
       min++; 
        console.log(oArray[i]); 
    } 
    //没有去重的原代码 
    // for(var i=0;i<num;i++){ 
    // result+=parseInt(Math.random()*(max-min+1) + min)+","; 
    // } 
    oArray.sort(function(){return 0.5 - Math.random(); })  //把按顺序存储的数组打乱 
    for(var i=0;i<num;i++){ 
    result+=oArray[i]+","; 
  } 
  document.getElementById("result").innerText=result; 
} 
</script> 
</html>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Array change detection issues in vue

History mode of vue project

The above is the detailed content of JS implements random number generation for deduplication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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