首页 > 解决方案 > 如果 null 在 funcion/while/try javascript 中不起作用,则提示验证

问题描述

如标题所述,在 func/while/try 中验证提示是否为空(inpname 变量)将不起作用。output = {} 同时我在外面做的测试工作正常。请检查下面的代码。我做错了什么?

//works
let test = prompt("testing","aasdasd");
if (test === null) {
  console.log("cancel");
}
else {
  console.log("ok");
}

let inpname;
//do not work
let func = () => {
  while (true) {
    try {
    inpname = prompt("name ", "name here");
    
    if (inpname.length > 10 || inpname.length <= 3) {
      throw "Your name must be at least 10 characters long, but not less than 4";
    }
    
    else if ( inpname != inpname.match(/^[a-zA-Z]+$/)) {
      throw "A-Z characters accepted only!";
    }
    
    //problem here!
    else if (inpname === null) {
      throw "cant cancel";
    }
    
    else {
      console.log("success");
      break
     }
  }
    catch (err) {
      console.log(err);
      break
    }
  }
}
func();

标签: javascript

解决方案


控制台输出{}而不是异常似乎是 Stack-snippets 中的一个错误。你会得到更正确的输出使用console.error.

话虽如此,您看到的问题部分是因为您在impname尝试取消引用之前没有检查它是否为空。

更改错误检查的顺序将解决问题(尽管堆栈片段仍然不会在发生异常时报告异常,这不是您在浏览器中获得的行为)

let func = () => {
    while(true) {
        var inpname = prompt("name ", "name here");
        
        try {
            if (inpname === null) {
                throw "cant cancel";
            }
            if (inpname.length > 10 || inpname.length <= 3) {
                throw "Your name must be at least 10 characters long, but not less than 4";
            }
            if (inpname != inpname.match(/^[a-zA-Z]+$/)) {
                throw "A-Z characters accepted only!";
            }
            return inpname;            
        } catch(err) {
            console.error(err);
        }
    }
}
func();

请注意,您可能希望避免禁止使用“取消”按钮。如果用户不想提供请求的信息,只需使用适当的消息退出应用程序


推荐阅读