Javascript - 我的密码检查器没有打印任何东西

时间:2018-04-27 14:10:17

标签: javascript json foreach

我对js很新。这是我第一次尝试有用的东西。这个概念很简单:准备一个json数组,然后循环遍历它。如果在一个循环中失败,则打印错误消息。我尝试运行此代码但没有任何反应:

num 1
num 2
end 3

2 个答案:

答案 0 :(得分:1)

您的代码中存在多个语法错误! - 缺少引号,括号太多......

然而,在您的代码的修正片段下面打印出您想要的行为:



var pass = "ji3or"; // strings need to be wrapped in quotes

function passCheck(pass) { // pass a variable to the function instead of relying on the global one
    var variations = {
        // add a proper key to reference it later and make it a valid object
        digits: { isValid: /\d/.test(pass), errorMsg: "Must contain at least 1 digit!" },
        lower: { isValid: /[a-z]/.test(pass), errorMsg: "Must contain at least 1 lower case letter!" },
        upper: { isValid: /[A-Z]/.test(pass), errorMsg: "Must contain at least 1 upper case letter!" },
        nonWords:{ isValid: /\W/.test(pass), errorMsg: "Must contain at least 1 non-letter symbol e.g. '@'!" } // use different quotes and not "@" or escape them with \"
    }

    for (var key in variations) {
        if(!variations[key].isValid) // you dont need a ternary operator, just check for a false value
            document.write(variations[key].errorMsg);
    }   
}

passCheck(pass);




答案 1 :(得分:0)

function passCheck(pass){
  if(pass.length<6){
    console.log("password too short")
  }
  else if(!/[A-Z]/.test(pass)){ 
    console.log("must contain uppercase letter")}
    else {
      console.log("all good")
    }
            }   
           
  passCheck("Asadasdasd"); 

您的功能写错了,这不是您通常应该验证密码的方式。以下是我将如何做到这一点