This article describes the method of automatically generating random strings containing numbers and characters in JavaScript. Share it for your reference. The details are as follows:
Here we mainly use two functions: Math.random() and Math.floor()
Math.random() -- Returns a pseudo-random number between 0 and 1 may be 0, but is always less than 1, [0,1)
Math.floor() -- round down and discard the value after the small number
Methods to implement random multi-digit numbers:
Copy the code as follows:/**
*
* Randomly generated numbers
*
*@param num generates the number of digits
*/
function randomNumber(num){
return ''+Math.floor(Math.random() * num) ;
}
javascript randomly generated characters
The following example is a random character that appears in the random AZ/az interval
Copy the code as follows:/**
*
* Random generation
*
*@param data json data example: {"start":0,"end":2,"number":5,"upper":true}
*@param start subscript
*@param end subscript
*@param number generates the number of bits
*@param upper Whether the uppercase is lowercase by default
*/
function randomLetter(data){
var letterData = "";
var lowercase = new Array("a","b","c","d","e","f","g","h","i","g","k","l","m","n","o","p","q","r","s","t","v","v","w","x","y","z");
var uppercase = new Array("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");
var start = data.start;
var end = data.end;
var number = data.number;
var upper = data.upper;
var length = end - start;
for(var i= 0;i < number; i++){
var index = Math.floor(Math.random() * length) + start;
var letter = "";
if(upper){
letter = uppercase[index];
}else{
letter = lowercase[index];
}
letterData += letter;
}
return letterData;
}
Quote:
The code copy is as follows: alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));
I hope this article will be helpful to everyone's JavaScript programming.