js随机生成6位验证码(大小写字母,数字)
你好! js随机生成6位验证码(大小写字母,数字),利用Math.random产生随机数。
代码如下
代码片.
function getRandom(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function getCode() {
let code = '';
for (var i = 0; i < 6; i++) {
var type = getRandom(1, 3);
switch (type) {
case 1:
code += String.fromCharCode(getRandom(48, 57));//数字
break;
case 2:
code += String.fromCharCode(getRandom(65, 90));//大写字母
break;
case 3:
code += String.fromCharCode(getRandom(97, 122));//小写字母
break;
}
}
return code;
};
console.log(getCode());//输出随机码
Unicode字符编码表
| 字符 | 编码 |
|---|---|
| 数字 | 48-57 |
| 小写字母 | 97-122 |
| 大写字母 | 65-90 |
大家可以复制代码测试一下哦!
本文介绍了一种使用JavaScript生成包含大小写字母及数字的六位验证码的方法。通过Math.random函数结合ASCII码范围,实现了随机字符的选择,适用于网站登录或表单验证等场景。

834

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



