在一个大型项目中,我通过显式检查是否使用 typeof 设置了变量来进行大量异常处理。这有点冗长,我想将我的习惯改为简单的真实:
if (myVar) {//do stuff}
在下面的代码段和其他一些测试中,它们似乎是等效的。然而,在我进行全面的代码更改(并替换数百个)之前,我想确认它们在逻辑上是等效的,并了解任何可能让我受益的边缘情况。
//What I have been doing
let myVar;
{
//other code that may or may not be able to give myVar a value
}
if (typeof(myVar) != "undefined"){
console.log("the value has been set, do more stuff");
} else {
console.log("the value was not set, handle the exception path");
}
//What I'd like to do
if (myVar) {
console.log("the value has been set, do more stuff");
} else {
console.log("the value was not set, handle the exception path");
}