This time I will show you how to generate random numbers with JS, and what are the precautions for generating random numbers with JS. The following is a practical case, let’s take a look.
var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
function generateMixed(n) {
var res = "";
for(var i = 0; i <p style="text-align: left;">1.Math.random(); The result is a random number between 0-1 (including 0, excluding 1)</p><p style="text-align: left;">2.Math.floor(num); Parameter num is a numerical value, and the function result is the integer part of num. </p><p style="text-align: left;">3.Math.round(num); The parameter num is a numerical value, and the function result is the integer after num is rounded. </p><p style="text-align: left;">Math: Mathematical object, providing mathematical calculations on data. </p><p style="text-align: left;">Math.random(); Returns a random number between 0 and 1 (including 0, excluding 1). </p><p style="text-align: left;">Math.ceil(n); Returns the smallest integer greater than or equal to n. </p><p style="text-align: left;">When using Math.ceil(Math.random()*10);, you mainly get random integers from 1 to 10, and the probability of getting 0 is very small. </p><p style="text-align: left;">Math.round(n); Returns the value of n after rounding. </p><p style="text-align: left;">Use Math.round(Math.random()); to obtain a balanced random integer from 0 to 1. </p><p style="text-align: left;">When using Math.round(Math.random()*10);, you can obtain random integers from 0 to 10 in a basically balanced manner, and the probability of obtaining the minimum value 0 and the maximum value 10 is less than half. </p><p style="text-align: left;">Math.floor(n); Returns the largest integer less than or equal to n. </p><p style="text-align: left;">When using Math.floor(Math.random()*10);, random integers from 0 to 9 can be obtained evenly. <br>Random example of random function for js to generate random numbers</p><p style="text-align: left;"><span style="color: #ff0000"><strong>JavaScript Math.random() built-in function</strong></span></p><pre class="brush:php;toolbar:false">random函数返回值
返回0和1之间的伪随机数,可能为0,但总是小于1,[0,1)
random函数示例
//返回随机数
document.write(Math.random());
//返回10-20的随机数
document.write(Math.random()*(20-10)+10);
//返回指定范围的随机数(m-n之间)的公式
document.write(Math.random()*(n-m)+m);Based on time, it can also be The code to generate a random number
is as follows:
var now=new Date(); var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。 var now=new Date(); var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。
Js The code to generate a 6-digit random number
is as follows:
<script>
function MathRand()
{
var Num="";
for(var i=0;i<6;i++)
{
Num+=Math.floor(Math.random()*10);
}
document.getElementById("Lb_Random").innerText=Num;
document.getElementById("Lb_Random").innerHTML=Num;
}
</script>Multiple ways to generate random strings with JS
The code is as follows:
<script>
function randomString(len) {
len = len || 32;
var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
var maxPos = $chars.length;
var pwd = '';
for (i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
document.write(randomString(32));
</script>It goes without saying how to use it, Call the randomString method, and the parameter len is the length of the returned random string.
The parameter passed is the length. If there is no parameter, the default output is 32 characters.
Several uses of JS to generate random numbers!
The code is as follows:
<script>
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(1,10);
alert(num);
</script>
var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
function generateMixed(n) {
var res = "";
for(var i = 0; i <p style="text-align: left;">1.Math.random(); The result is a random number between 0-1 (including 0, excluding 1) <br>2.Math.floor(num); The parameter num is a numerical value, and the function result is the integer part of num. <br>3.Math.round(num); The parameter num is a numerical value, and the function result is the integer after num is rounded. </p><p style="text-align: left;">Math: Mathematical object, providing mathematical calculations on data. <br>Math.random(); Returns a random number between 0 and 1 (including 0, excluding 1). </p><p style="text-align: left;">Math.ceil(n); Returns the smallest integer greater than or equal to n. <br>When using Math.ceil(Math.random()*10);, you mainly get random integers from 1 to 10, and the probability of getting 0 is very small. </p><p style="text-align: left;">Math.round(n); Returns the value of n after rounding. <br>Use Math.round(Math.random()); to obtain a random integer from 0 to 1 evenly. <br>When using Math.round(Math.random()*10);, random integers from 0 to 10 can be obtained in a basically balanced manner, and the probability of obtaining the minimum value 0 and the maximum value 10 is less than half. </p><p style="text-align: left;">Math.floor(n); Returns the largest integer less than or equal to n. <br>When using Math.floor(Math.random()*10);, random integers from 0 to 9 can be obtained evenly. </p><p style="text-align: left;"><span style="color: #ff0000"><strong>js generates a random string timestamp to obtain</strong></span></p><p style="text-align: left;">The default JS generated is 13 digits, which needs to be passed to php/1000</p><p style="text-align: left;">The code is as follows:</p><pre class="brush:php;toolbar:false">timestamp = timestamp/1000;
<script>
function randomChar(l) {
var x="0123456789qwertyuioplkjhgfdsazxcvbnm";
var tmp="";
var timestamp = new Date().getTime();
for(var i=0;i< l;i++) {
tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
}
return timestamp+tmp;</script>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:
How to make infinite loading data requirements at the bottom of the sliding page
##Using vue-devtools from scratch
The above is the detailed content of How to generate random numbers in JS. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)






