本文实例讲述了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程序设计有所帮助。