当没有匹配时,我无法打印单个输出语句。目前,如果没有匹配(密码中没有数字),它将多次打印,直到找到匹配为止。
有人可以看看下面我的困境:
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
while (i < password.length) {
if (password[i] == password.match(/[0-9]/g)) {
console.log("found: " + password[i]);
} else {
console.log("not found");
}
i++;
}
}
}
答案 0 :(得分:3)
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var found = false;
while (i < password.length) {
if (password[i].match(/[0-9]/g)) {
found = true;
break;
}
i++;
}
if(found) {
console.log("found");
} else {
console.log("not found");
}
}
}
但是,如果你只是在字符串中寻找一个数字,你最好这样做:
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else if(!password.match(/[0-9]{1,}/)) {
console.log("password should contain at least one number");
} else {
console.log("okay");
}
}
这是一个JSFiddle:https://jsfiddle.net/7btt1axb/
答案 1 :(得分:0)
这样的东西?
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var i = 0, found = false;
while (i < password.length && !found) {
if (password[i] == password.match(/[0-9]/g)) found = true;
else i++;
}
if (found) {
console.log("found: " + password[i]);
} else console.log("not found");
}
}
checkPassword(password);
&#13;