隨機生成一個四位數的驗證碼
阿新 • • 發佈:2020-12-27
技術標籤:javascriptrandom
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function getstr(len){
var template = '';//將所有可選的字元儲存起來
for(var i = 65;i < 65 + 26; i++){
template += String.fromCharCode(i); //A~Z對應的Unicode碼
}
for(var i = 97; i < 97 + 26; i++){
template += String.fromCharCode(i); //a~z
}
for(var i = 48; i < 48 + 10; i++){
template += String.fromCharCode(i); //0~9
}
var result = "";
for(var i = 0; i < len; i++){
var index = getnumber(0, template.length - 1); //隨機獲取一個下標
result += template[index];
}
return result;
}
function getnumber(min, max){
return Math.floor((Math.random() * (max - min +1) + min));
}
var strings = getstr(4); //獲取一個4位數
console.log(strings)
</script>
</body>
</html>