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

有些时候需要判断类型是否为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}`)

在这里插入图片描述

在有些文章里看到了下面这种方法,思路是通过排除来确定类型为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不和任何一个值相等,包括它自己

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六时二一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值