JavaScript/TypeScript对象的空值检查

4
在以下两种方式中进行空值检查时,是否存在性能差异 -
if (!someObject) {
   // dosomething
}

vs

if (someObject != null) {
   // dosomething
}

如果你的问题是关于性能的,为什么不直接测量它呢? - trincot
@Yousuf 请阅读 https://github.com/rwaldron/idiomatic.js 中的“4.条件语句”部分。 - wf9a5m75
@wf9a5m75 感谢提供链接,看起来是一个不错的资源。 - Yousuf
2个回答

8

!someObject 检查所有假值。

Not ( empty string, undefined, null, 0, false) - will all pass the condition

第一个条件仅检查是否为null,而第二个条件则检查更多情况。

 if (someObject !== null) {
    console.log('falsey');
 }

 someObject = null;      // no message in console
 someObject = '';        // falsey
 someObject = undefined; // falsey
 someObject = 0;         // falsey
 someObject = false;     // falsey

假值检查

if (!someObject) {
    console.log('falsey');
 }

 someObject = null;      // no message in console
 someObject = '';        // no message in console
 someObject = undefined; // no message in console
 someObject = 0;         // no message in console
 someObject = false;     // no message in console

由于 !someObject 会评估所有 truthy 值,这是否意味着当我只需要检查 null 时它不够高效? - Yousuf
由于这只是一个简单的检查,因此对于这两种情况,性能都将可以忽略不计。 - Sushanth --
好的,我也这么想。我的同事告诉我这样不够高效,所以我有些疑惑。 - Yousuf
3
你的同事可能更关心你的表现以及你对隐式类型转换的依赖,以判断 null 或 undefined 的值。(我是你的同事) - alan
1
顺便说一下,Benchmark.js显示差异大约为16%(Chrome,someObject = {})。只要someObject不为空,第一种选项更快。如果为空,则第二种选项更快:https://jsbench.me/tiizafwdy4 - Mirko Vukušić

0

为了正确检查空值,您需要编写:

  if(!someobject && typeof someobject!== "object") 
理想情况下,typeof null不应该返回"object"。 You Don't Know JS中的类型和语法章节提到:

JS 中的这个原始 bug 已经存在了近二十年,很可能永远都不会被修复,因为有许多现有的 web 内容依赖于其错误的行为,“修复”这个 bug 将创建更多的“bug”,并破坏大量的 web 软件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接