如果 null 在 funcion/while/try JavaScript 中不起作用,则提示验证



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

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

控制台输出{}而不是异常似乎是堆栈片段中的一个错误。 使用console.error您将获得更正确的输出。

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

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

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

请注意,您可能希望避免禁止使用"取消"按钮。 如果用户不想提供请求的信息,只需退出应用并显示相应的消息即可

最新更新