前端JS生成随机数(字母加数字)
自己想了一个比较简单的办法,没有用ASCII码转换。转换方法: String.fromCharCode(...number),类似于Java的(char)number。
created() {
let total = 15;
console.log('生成的长度:',total);
for (let i = 0; i < 10; i++) {
console.log(this.generateRandomNumbers(total));
}
},
/**
* 方法作用: 生成随机数
* 创建时间: 2019-05-28
* 创建人:Cr
* @param total 要生成的长度 / 几位随机数
* */
generateRandomNumbers(total){
let that = this;
// 如果不传total或者传0,设置成10位。
total = total == undefined || total == 0 ? 10 : total;
let str = '';
for (let i = 0; i < total; i++) {
let number = parseInt(Math.random() * 35);
// 当前生成的随机数大于等于10则进行转换。
if(number >= 10){
str += that.numberConvertEnglishLetters(number);
}else{
str += number.toString();
}
}
return str;
},
/**
* 方法作用: 数字转换成英文字母
*
* 创建时间: 2019-05-28
*
* 创建人:Cr
* */
numberConvertEnglishLetters(number){
let map = this.numberConvertEnglishLettersMap();
for (let i = 0; i < map.length; i++) {
if(map[i].key == number){
return map[i].value;
}
}
},
/**
* 方法作用: 数字转换成英文字母的映射关系Map
*
* 创建时间: 2019-05-28
*
* 创建人:Cr
* */
numberConvertEnglishLettersMap(){
return [
{'key':10,'value':'a'},
{'key':11,'value':'b'},
{'key':12,'value':'c'},
{'key':13,'value':'d'},
{'key':14,'value':'e'},
{'key':15,'value':'f'},
{'key':16,'value':'g'},
{'key':17,'value':'h'},
{'key':18,'value':'i'},
{'key':19,'value':'j'},
{'key':20,'value':'k'},
{'key':21,'value':'l'},
{'key':22,'value':'m'},
{'key':23,'value':'n'},
{'key':24,'value':'o'},
{'key':25,'value':'p'},
{'key':26,'value':'q'},
{'key':27,'value':'r'},
{'key':28,'value':'s'},
{'key':29,'value':'t'},
{'key':30,'value':'u'},
{'key':31,'value':'v'},
{'key':32,'value':'w'},
{'key':33,'value':'x'},
{'key':34,'value':'y'},
{'key':35,'value':'z'},
];
},
附上效果图:
版权声明:本文为qq_36255237原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。