原生JS生成指定位數(shù)的驗證碼
使用原生JS生成指定位數(shù)的驗證碼,驗證碼包括字母和數(shù)字
##思路:使用String的fromCharCode方法將給定范圍的隨機數(shù)轉為大小寫字母,再通過隨機數(shù)決定數(shù)組當前位置為大寫字母,小寫字母或者是數(shù)字,函數(shù)傳入的參數(shù)當做該數(shù)組的長度,隨機填好數(shù)組后,對數(shù)組內(nèi)的元素做分情況處理:當該數(shù)組內(nèi)沒有數(shù)字時,需要隨機修改一個字母為一個隨機的數(shù)字;當該數(shù)組沒有字母時,需隨機修改一個數(shù)字為大寫或者小寫字母;正常情況下的有字母也有數(shù)字不做處理,每個判斷語句的最后使用數(shù)組的join方法將該數(shù)組轉換為字符串并return。
function verificationCode(num) {
var arr = [];
var letterFlag = false;
var numberFlag = false;
for (i = 0; i < num; i++) {
// 獲取隨機大寫字母
var uppercase = String.fromCharCode(Math.round(Math.random() * 25 + 65));
// 獲取隨機小寫字母
var lower = String.fromCharCode(Math.round(Math.random() * 25 + 97));
// 獲取隨機數(shù)字
var number = Math.round(Math.random() * 9);
// 獲取0-2的隨機數(shù)來隨機決定該位置是大寫字母,小寫字母或者是數(shù)字
var temp = Math.round(Math.random() * 2)
if (temp == 0) {
arr[i] = uppercase;
} else if (temp == 1) {
arr[i] = lower;
} else {
arr[i] = number;
}
}
// 檢查arr是否同時有字母與數(shù)字
for (var j = 0; j < arr.length; j++) {
if (Object.prototype.toString.call(arr[j]) == "[object String]") {
letterFlag = true;
}
if (typeof(arr[j]) == 'number') {
numberFlag = true;
}
}
// 對不同情況做處理
// 字母數(shù)字都有
if (letterFlag && numberFlag) {
return arr.join("");
}
// 沒有字母時
if (letterFlag == false && numberFlag == true) {
uppercase = String.fromCharCode(Math.round(Math.random() * 25 + 65));
lower = String.fromCharCode(Math.round(Math.random() * 25 + 97));
temp = Math.round(Math.random() * 1)
if (temp == 0) {
arr[Math.round(Math.random() * (num - 1))] = uppercase;
} else {
arr[Math.round(Math.random() * (num - 1))] = lower;
}
return arr.join("");
}
// 沒有數(shù)字時
if (letterFlag == true && numberFlag == false) {
number = Math.round(Math.random() * 9);
arr[Math.round(Math.random() * (num - 1))] = number;
return arr.join("");
}
}
var code = verificationCode(10);
console.log(code);
運行結果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
javascript 動態(tài)數(shù)據(jù)下的錨點錯位問題解決方法
用 Javascript 實現(xiàn)錨點(Anchor)間平滑跳轉2008-12-12

