檢查 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