本文實例講述了javascript自動產生包含數字與字元的隨機字串的方法。分享給大家供大家參考。具體如下:
這裡主要用到Math.random() 和 Math.floor() 兩個函數
Math.random() -- 傳回0和1之間的偽隨機數 可能為0,但總是小於1,[0,1)
Math.floor() -- 向下取整,捨去小數字後的值
實作隨機多位數的方法:
/**
*
* 隨機產生數字
*
*@param num 產生數字位數
*/
function randomNumber(num){
return '' Math.floor(Math.random() * num) ;
}
javascript 隨機產生字元
以下實例為隨機 A-Z / a-z區間 中隨機出現的字元
/**
*
* 隨機產生
*
*@param data json資料 範例:{"start":0,"end":2,"number":5,"upper":true}
*@param start 開始下標
*@param end 結束下標
*@param number 產生位數
*@param upper 是否大寫 預設為小寫
*/
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
var index = Math.floor(Math.random() * length) start;
var letter = "";
if(upper){
letter = uppercase[index];
}else{
letter = lowercase[index];
}
letterData = letter;
}
return letterData;
}
引用:
alert(new Date().Format("yyyy-MM-dd hh:mm :ss"));
希望本文所述對大家的javascript程式設計有所幫助。