本文實例講述了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 < 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;
}
引用:
代碼如下:alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));
希望本文所述對大家的javascript程序設計有所幫助。