Home > Web Front-end > JS Tutorial > JavaScript automatically generates random strings containing numbers and characters_javascript skills

JavaScript automatically generates random strings containing numbers and characters_javascript skills

WBOY
Release: 2016-05-16 16:15:10
Original
1355 people have browsed it

The example in this article describes how javascript can automatically generate a random string containing numbers and characters. Share it with everyone for your reference. The details are as follows:

The two functions Math.random() and Math.floor() are mainly used here

Math.random() -- Returns a pseudo-random number between 0 and 1. It may be 0, but it is always less than 1, [0,1)

Math.floor() -- round down and discard the decimal value

Method to implement random multi-digit numbers:

Copy code The code is as follows:
/**
*
* Randomly generated numbers
*
*@param num Number of generated digits
*/
function randomNumber(num){
           return '' Math.floor(Math.random() * num) ;
}

javascript randomly generates characters

The following examples are random characters appearing in the random A-Z / a-z range

Copy code The code is as follows:
/**
*
* Randomly generated
*
*@param data json data Example: {"start":0,"end":2,"number":5,"upper":true}
*@param start Start subscript
*@param end End subscript
*@param number Number of generated digits
*@param upper Whether it is uppercase or not. The default is lowercase
​*/
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","u","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:


Copy code The code 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 design.
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