Home > Web Front-end > JS Tutorial > JavaScript random number generator implementation method

JavaScript random number generator implementation method

小云云
Release: 2018-01-29 10:47:58
Original
2278 people have browsed it

This article mainly introduces the JavaScript implementation of a random number generator in detail to generate non-repeating random numbers. It has a certain reference value. Interested friends can refer to it. I hope it can help everyone.

1. Preparation before experiment:

Understanding of Math function

Understanding of array method

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>
Copy after login

3. Operation results

Related recommendations:

How to generate random numbers using javascript Method summary

php rand() function for random number generation

JavaScript implementation of random number deduplication generator

The above is the detailed content of JavaScript random number generator implementation method. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template