JavaScript 判断 null 、undefined、NaN的可靠方法、验证以及注意事项

340 阅读1分钟

有些时候需要判断类型是否为null、undefined或者NaN,常用的方法有以下:

判断方法

判断undefined

使用typeof

typeof xxx === 'undedfined'

在这里插入图片描述

注意:typeof无法判断null,并且 typeof null 会得到'object'

在这里插入图片描述


判断null

value == nullvalue === null

let value = null
console.log(value)
console.log(`the type of value is ${value==null}\nthe type of value is ${value===null}`)

在这里插入图片描述

在CSDN有些文章里看到了下面这种方法,思路是通过排除来确定类型为null,但实际上是不严谨的

!value && value!=0 && typeof value!='undefined'

let value = null
console.log( `Is the type of value null? ${ !value && value!=0 && typeof value!='undefined' }` )

在这里插入图片描述 许多笔记里基本都是给的这个式子,看上去好像没有问题,但实际上这是错的。

js中,当参数为: undefined0false'' 或者 ""NaNnull时,转为布尔值会得到false

上面的式子可以排除undefined0false''"",但是不能排除NaN,也就是说当参数值为NaN或者null时,上面的逻辑运算式都会得到true,请看以下:

function check(value){
	return !value && value!=0 && typeof value!='undefined'
}

console.log(`Boolean(NaN) is ${Boolean(NaN)}, Boolean(null) is ${Boolean(null)}`)
console.log(`check(null) is ${check(null)}, but check(NaN) is ${check(NaN)}`)

在这里插入图片描述 所以这种方法并不严谨

判断NaN

isNaN(value) //就这一个

在这里插入图片描述

注意事项

undefined和null和比较

使用===

在这里插入图片描述

NaN和自己比较

请注意,NaN不和任何一个值相等,包括它自己

在这里插入图片描述