0

在一个大型项目中,我通过显式检查是否使用 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");
}

4

4 回答 4

2

这个:

if (myVar) {}

将在所有虚假值上返回 false ,例如空字符串 ( "")、零 ( 0)、false, null,当然还有undefined.

如果您不希望上述任何值通过您的if语句,那么是的,它在逻辑上是等价的。

但是,我会说这是一个大胆的声明,您的任何if声明都不会包含0or ""。这些是共同的价值观。

如果您想清理此代码并继续仅检查undefined,那么您可以跳过类型检查并仅检查:

if (myVar === undefined) {}
于 2020-12-11T04:17:10.590 回答
1

他们可以看起来那样,但可能不会像您期望的那样。

这里有一些进一步的证明:

const tests = [false, undefined, null, '', NaN, 0, -0, 0n, 'anything else'];
tests.map(t=> console.log(t ? t + ' is truthy' : t + ' is falsy'));

于 2020-12-11T04:16:34.437 回答
0

不,因为在这种情况下if(myVar)ifmyVar = 0, false, "",undefined将返回 false。并且if (typeof(myVar) != "undefined")当返回 false 时myVar = undefined

于 2020-12-11T04:15:25.537 回答
0

使用感叹号,您可以检查该变量是否为相反的布尔值,例如 undefined、false、空字符串、null 和 0 是假值

let myVar = undefined;
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

myVar = '';
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

myVar = false;
if(!myVar){
    console.log('type of: ' + typeof(myVar))
}   

于 2020-12-11T04:20:22.743 回答