javascript自动生成包含数字与字符的随机字符串

时间:2021-05-26

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章