在以下两种方式中进行空值检查时,是否存在性能差异 -
if (!someObject) {
// dosomething
}
vs
if (someObject != null) {
// dosomething
}
if (!someObject) {
// dosomething
}
vs
if (someObject != null) {
// dosomething
}
!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 = {}
)。只要someObject
不为空,第一种选项更快。如果为空,则第二种选项更快:https://jsbench.me/tiizafwdy4 - Mirko Vukušić为了正确检查空值,您需要编写:
if(!someobject && typeof someobject!== "object")
理想情况下,typeof null
不应该返回"object"。
You Don't Know JS中的类型和语法章节提到:
JS 中的这个原始 bug 已经存在了近二十年,很可能永远都不会被修复,因为有许多现有的 web 内容依赖于其错误的行为,“修复”这个 bug 将创建更多的“bug”,并破坏大量的 web 软件。