1.使用Math.random()生成随机数
2.toString(36) 转换成36进制
3.然后使用slice()截取出来
Math.random().toString(36).slice(2,10)
方法二 对定义的数组字符集进行随机选取
let str = ['0','1','2','3','4','5','6','7','8','9','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'];
function randomString(n) {
let res = "";
for(let i = 0; i < n ; i ++) {
let id = Math.ceil(Math.random()*35);
res += str[id];
}
return res;
}
console.log(randomString(6));
本文介绍了两种在JavaScript中生成随机字符串的方法:一种是利用Math.random()结合toString(36)和slice()创建指定长度的36进制字符串;另一种是通过遍历预定义的字符集随机选取字符。这两种方法都可用于生成安全的唯一标识符或其他需要随机字符串的场景。
2878

被折叠的 条评论
为什么被折叠?



