2017-01-13 1 views
-2

일치하는 것이없는 경우 단일 출력 문을 인쇄 할 수 없습니다. 현재 일치하는 항목이 없으면 (암호 포함 안 함) 매치를 찾을 때까지 여러 번 인쇄됩니다.JavaScript - While 루프 문이 여러 번 인쇄됩니다.

사람이하시기 바랍니다 이하 나의 딜레마에서 살펴 수 : 당신은 단지 문자열에 숫자를 찾고 있다면,

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++; 
    } 
    } 
} 
+1

루프가 아무 의미 동안이 체크. – dfsq

+0

가장 효율적인 방법 중 하나는 루프 다음에 log 문을 배치하는 것입니다. – Teemu

답변

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

두 번째 코드 예제가 작동하는 동안 코드 예제에서 첫 번째 코드 예제를 실행할 때'if (password [i]! = password.match (/ [0-9]/g)) {'항상 '암호에 숫자가 있거나 아직 작동하지 않는 경우. – Nope

+1

네, 너무 썼습니다. 이제 해결되었습니다. –

+0

대단히 감사합니다! 그게 정확히 내가 찾던거야. 나는 코드의 단순함을 좋아한다! –

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);

+0

각 문자를'password.match (/ [0-9]/g) '로 반복 할 필요가 없습니다. 어떤 숫자라도 감지 할 것입니다 일치하는 항목이있는 배열을 반환하고, 일치하는 항목이 없으면 if 문과 관련하여'false'로 간주되는'null'이 반환됩니다. – Nope

+0

사실, 당신 말이 맞습니다. ssc-hrep3의 대답은 갈 길입니다. 나는 그를 뽑았다. –