检查 JavaScript 中的变量是否不为空
Harshit Jindal
2023年10月12日

本教程讲解如何在 JavaScript 中检查变量是否不为空。
看似正确的错误方法
if (myVar) {
...
}
当 myVar
为 null
时,这种方式将评估为 true
,但是当 myVar
为以下任何一种时,它也将被执行:
undefined
null
0
""
(空字符串)false
NaN
检查变量是否为空的正确方法
if (myVar !== null) {
...
}
上面的代码是检查变量是否为 null
的正确方法,因为只有在变量实际上为 null
时才会被触发。
作者: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn