Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript/typescript对象空检查_Javascript_Typescript - Fatal编程技术网

javascript/typescript对象空检查

javascript/typescript对象空检查,javascript,typescript,Javascript,Typescript,在以下两种方式中执行空检查时,性能是否存在差异- if (!someObject) { // dosomething } vs !someObject检查所有错误值 Not ( empty string, undefined, null, 0, false) - will all pass the condition 其中,作为第一个条件,仅检查null if (someObject !== null) { console.log('falsey'); } someOb

在以下两种方式中执行空检查时,性能是否存在差异-

if (!someObject) {
   // dosomething
}
vs


!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

要正确检查空值,您必须写入:

 if(!someobject && typeof someobject!== "object")
if(!someobject&&typeof someobject!==“object”)
理想情况下,
typeof null
不应返回“object”

中的类型和语法一章提到:

JS中的这个原始错误已经持续了近二十年,而且可能永远不会被修复,因为有太多现有的web内容依赖于它的错误行为,“修复”这个错误会产生更多的“错误”,并破坏很多web软件


如果你的问题是关于性能的,为什么不直接测量一下呢?@Yousuf在“4.Conditional Evaluation”阅读@wf9a5m75谢谢你的链接,看起来是一个很好的资源。因为!someObject正在评估所有的真实值,这是否意味着当我只需要检查null值时它就没有那么有效了?因为这只是一个简单的检查,在这两种情况下性能都可以忽略不计,好吧,我想是的。我的同事告诉我它效率不高,所以我想知道。@Yousuf你同事关心的可能更多的是性能的结合,以及你对隐式类型转换的依赖,以计算空值或未定义的值。(我是你的同事)顺便说一句,Benchmark.js说大约有16%的差异(Chrome,
someObject={}
)。只要someObject不为null。如果为空,则第二个选项更快:
 if(!someobject && typeof someobject!== "object")