JS生成隨機字符串的多種方法


 1 <script language="javascript"> 
 2 function randomString(len) {
 3   len = len || 32;
 4   var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默認去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
 5   var maxPos = $chars.length;
 6   var pwd = '';
 7   for (i = 0; i < len; i++) {
 8     pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
 9   }
10   return pwd;
11 }
12 document.write(randomString(32));
13 </script> 

調用randomString方法,參數len為返回的隨機字符串長度。

JS產生隨機數的幾個用法!

 1 <script>   
 2 function GetRandomNum(Min,Max)
 3 {   
 4 var Range = Max - Min;   
 5 var Rand = Math.random();   
 6 return(Min + Math.round(Rand * Range));   
 7 }   
 8 var num = GetRandomNum(1,10);   
 9 alert(num);   
10 </script>
11 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'];
12 
13 function generateMixed(n) {
14      var res = "";
15      for(var i = 0; i < n ; i ++) {
16          var id = Math.ceil(Math.random()*35);
17          res += chars[id];
18      }
19      return res;
20 }

1.Math.random(); 結果為0-1間的一個隨機數(包括0,不包括1) 
2.Math.floor(num); 參數num為一個數值,函數結果為num的整數部分。 
3.Math.round(num); 參數num為一個數值,函數結果為num四舍五入后的整數。

Math:數學對象,提供對數據的數學計算。
Math.random(); 返回0和1間(包括0,不包括1)的一個隨機數。

Math.ceil(n); 返回大於等於n的最小整數。
用Math.ceil(Math.random()*10);時,主要獲取1到10的隨機整數,取0的幾率極小。

Math.round(n); 返回n四舍五入后整數的值。
用Math.round(Math.random());可均衡獲取0到1的隨機整數。
用Math.round(Math.random()*10);時,可基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的幾率少一半。

Math.floor(n); 返回小於等於n的最大整數。
用Math.floor(Math.random()*10);時,可均衡獲取0到9的隨機整數。

js生成隨機字符串+時間戳獲取

默認JS生成的是13位,傳給php需要 /1000

 1 timestamp = timestamp/1000;
 2 <script type="text/javascript">
 3 function  randomChar(l)  {
 4 var  x="0123456789qwertyuioplkjhgfdsazxcvbnm";
 5 var  tmp="";
 6 var timestamp = new Date().getTime();
 7 for(var  i=0;i<  l;i++)  {
 8 tmp  +=  x.charAt(Math.ceil(Math.random()*100000000)%x.length);
 9 }
10 return  timestamp+tm

 

原文:https://www.jb51.net/article/50910.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM