要专门检查空值,您将使用以下命令:
if (variable === null)
此测试将仅通过 , 、 、 或 。null
""
undefined
false
0
NaN
此外,我还为每个“类似 false”的值提供了绝对检查(一个将返回 true 的值)。!variable
请注意,对于某些绝对检查,您需要实现使用 和 。absolutely equals: ===
typeof
我在这里创建了一个JSFiddle来展示所有单独的测试工作
以下是每个检查的输出:
Null Test:
if (variable === null)
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if (variable === '')
- variable = ''; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if (typeof variable == "undefined")
-- or --
if (variable === undefined)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if (variable === false)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if (variable === 0)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)
-- or --
if (isNaN(variable))
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
如您所见,测试起来有点困难NaN
;