javascript - 如果 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();
解决方案
控制台输出{}
而不是异常似乎是 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();
请注意,您可能希望避免禁止使用“取消”按钮。如果用户不想提供请求的信息,只需使用适当的消息退出应用程序
推荐阅读
- php - 没有主题页眉、页脚、侧边栏的完整 Wordpress Post html、脚本和 css
- html - 如何修复这个“Tailwind CSS Deprecation”错误?
- c# - 可以做些什么来防止此 MailKit SMTP 失败?
- reactjs - reactjs中未从父级调用子组件函数
- c++ - C++ 对编译的多重定义
- tensorflow - tensorflow(lambda 文本,标签:文本)仅文本并使用 pyspark 进行调整
- bash - npm 不会安装 sass 并且无法输入密码
- c# - azure 函数应用程序中的 LINQ 子查询返回错误消息
- sql-server - 外部应用内的 WITH 语句
- node.js - 如何从文件夹中删除已添加的 developer-pop?