Multiple ways in which JS generates random strings

  • 2020-03-30 03:19:20
  • OfStack

The following code, when the computer, records for reference.


<script language="javascript"> 
function randomString(len) {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    
  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> 

Using methods, needless to say, calls the randomString method with len as the returned randomString length.

Pass parameters on the length, if no parameters default output 32 characters.

A few USES of JS to generate random Numbers!


<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 < n ; i ++) {
         var id = Math.ceil(Math.random()*35);
         res += chars[id];
     }
     return res;
}

1. Math. The random (); A random number between 0 and 1 (including 0, not including 1)
2. Math. Floor (num); The parameter num is a numeric value, and the result of the function is the integer part of num.
3. Math. Round (num); The parameter num is a numeric value and the result of the function is the rounded integer of num.

Math: Math object that provides mathematical calculations of data.
Math. The random (); Returns a random number between 0 and 1 (including 0, not including 1).

Math. Ceil (n); Returns the smallest integer greater than or equal to n.
Use Math. Ceil (Math. The random (10); , it mainly gets random integers from 1 to 10, and the probability of taking 0 is very small.

Math. Round (n); Returns the value of the rounded integer n.
Use Math. Round (Math. The random ()); The random integer from 0 to 1 can be obtained equitably.
Use Math. Round (Math. The random (10); When, random integers from 0 to 10 can be obtained in basic equilibrium, in which the probability of obtaining the minimum value 0 and the maximum value 10 is less than half.

Math. Floor (n); Returns the largest integer less than or equal to n.
Use Math. Floor (Math. The random (10); , the random integer from 0 to 9 can be obtained equitably.

Js generates random string + timestamp fetch

The default JS generation is 13 bits, and it takes /1000 to pass to PHP


timestamp = timestamp/1000;
<script type="text/javascript">
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;


Related articles: