检查某个内容是否为null或未定义的最佳方法



我想知道,在JSON数组或对象中检查某个内容是否为null或未定义的最佳方法是什么?多年来我一直在使用

if (value !== null && value !== undefined) {
// Value isn't null or undefined
}

您只需使用松散相等运算符==
它会将nullundefined视为相同。

if (value != null) {
/* do something with the value if it isn't null AND undefined */
}
if (value == null) {
/* do something with the value if it is null OR undefined */
}
// Which is the same as this one with the strict equality operator
if (value !== null && value !== undefined) {
/* do something with the value if it isn't null AND undefined */
}
if (value === null || value === undefined) {
/* do something with the value if it is null OR undefined */
}

IMHO将typeof用于undefined是最安全的方式,因为它根本不需要声明变量。然后可以添加value !== null,所以如果声明了value,则检查它是否不是Null。当然,这取决于您的项目细节、代码风格等,而不存在"最好的";。。。但是,如果您的环境预计会出现这样的情况,即变量不能被声明,或者您有一些动态函数生成,请记住,typeof value !== "undefined"将处理未声明的变量。

if (typeof value !== "undefined" && value !== null) {
console.log("exist and not Null");
} else {
console.log("not exist or Null");
}

下面是一个例子,如果不使用typeof:,它将抛出错误

if (value !== undefined && value !== null) {
console.log("exist and not Null");
} else {
console.log("not exist or Null");
}

相关内容

最新更新