2 回答
TA贡献2080条经验 获得超4个赞
有多种方法,正如您从其他人的各种建议中看到的那样,这取决于您想要完成什么以及您的代码在做什么。
||如果提供的输入undefined如下所示,您可以使用 or ( ) 运算符回退到默认/安全值
let userInput; //undefined`
let x = userInput || "a safe value";
本质上,“让 x 成为 userInput 的任何内容,除非它是undefined(或NaN,,null...)。
同样,您可以进行if检查以确保您期望的值可用且有效:
if(userInput){
//Happy path, userInput is valid.
}
else {
// Not so happy path, do something about it to handle the invalid value.
}
try-catch如果你想处理这个案例,你可以使用一个块。有多种抛出、捕获和处理错误的方法,但如果你想通知用户他们的输入无效,你可以这样做:
try {
//stuff may happen here
if(userInput) {
throw new TypeError("A useful description of why this was thrown");
}
//if userInput is value, then continue...
}
catch(error){
alert("Oops! Seems like the value you entered is not valid. Error:" + error);
}
注意:如果您不确定什么是最好的方法,那么如果您能为我们提供更多代码和上下文将会很有用,这样我们就可以在确定处理此问题的最佳方法之前了解如何以及何时分配值.
看起来您正试图在用户有机会输入之前访问用户的输入数据,在这种情况下,重构您的代码会更好。
添加回答
举报