此函数的好处是可以指定任意长度,任意值的范围
代码:不满足你的需求或者有不足的可以评论留言
random(16); //调用函数:指定长度为16位
function random(length) {
length || (length = 8); //指定长度: 默认长度8位
const numbers = '0123456789'; //指定数字范围,
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //指定字母范围,(也可以指定字符或者小写字母)
let total = '';
total += numbers += letters; //将数字和字母合并成一个字符串
let result = '';
//从合并的字符串里随机取出一个值
while (length > 0) { //循环次数是指定长度
length--;
result += total[Math.floor(Math.random() * total.length)];
}
console.log("生成的随机字符串:" + result);
return result;
}
结果: