哪种方式更好地检查JavaScript中的未定义变量?

huangapple go评论86阅读模式
英文:

Which is the better way to check undefined in Javascript?

问题

我之前一直像这样检查 `undefined` 值:

if(variable !== 'undefined')

然后我遇到了下面的代码:

if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')

我采用了相同的约定,因为我知道当变量未声明时这样更安全。但在我的代码审查中,有人指出我可以简单地写成:

if(variable1 || variable2)

这些方式中哪一个是最标准的检查 `undefined` 的方式?
英文:

I had been checking for undefined values myself like:

if(variable !== 'undefined')

then I came across the following code:

if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')

I followed the same convention knowing it's safer when variable goes undeclared. While in my code reviews, it was pointed I could simple write:

if(variable1 || variable2)

Which of these is the most standard way to check undefined?

答案1

得分: 2

有以下各种用例

  1. if (variable) 是在JavaScript中检查任何变量的真实性的标准方式。您可以在Truthy | MDN Web Docs中找到哪些值将是真实的示例。另请参考Falsy | MDN Docs

  2. 明确检查未定义的情况是当变量已声明但未分配值或明确分配了undefined时。在这种情况下,请使用if (variable !== undefined)

  3. 如果您从API接收响应,该响应可能包含字符串化的undefined值,您可以确定,那么只需执行检查if (variable !== 'undefined')

英文:

There are various use case as following

  1. if (variable) is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN Docs

  2. The cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned undefined.
    In that case use if (variable !== undefined).

  3. If you are receiving response from an API which might consist of stringified value of undefined, which you are sure of, then only do the check if (variable !== 'undefined')

huangapple
  • 本文由 发表于 2020年1月3日 13:50:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定