JS中判断null、undefined与NaN的方法
作者:whsnow 时间:2024-04-19 09:54:27
写了个 str ="s"++;
然后出现Nan,找了一会。
收集资料如下判断:
1.判断undefined:
var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}
说明:typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"
2.判断null:
var tmp = null;
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){
alert("null");
}
3.判断NaN:
var tmp = 0/0;
if(isNaN(tmp)){
alert("NaN");
}
说明:如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符。
提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。
4.判断undefined和null:
var tmp = undefined;
if (tmp== undefined)
{
alert("null or undefined");
}
var tmp = undefined;
if (tmp== null)
{
alert("null or undefined");
}
说明:null==undefined
<!--EndFragment-->
5.判断undefined、null与NaN:
var tmp = null;
if (!tmp)
{
alert("null or undefined or NaN");
}
提示:一般不那么区分就使用这个足够。
标签:null,undefined,NaN
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python中使用enumerate函数遍历元素实例
2021-05-08 04:56:41
微信小程序实现分页查询详解
2024-04-16 10:38:58
![](https://img.aspxhome.com/file/2023/0/136570_0s.png)
老生常谈js中0到底是 true 还是 false
2024-05-11 09:44:12
Python用SSH连接到网络设备
2022-01-20 08:57:41
![](https://img.aspxhome.com/file/2023/1/89191_0s.png)
Go实现简易RPC框架的方法步骤
2024-04-26 17:16:33
Python+random模块实现随机抽样
2022-01-19 23:58:20
![](https://img.aspxhome.com/file/2023/4/92374_0s.jpg)
Python单元测试简单示例
2021-07-27 12:03:11
基于python检查SSL证书到期情况代码实例
2023-06-26 06:23:58
利用python实现平稳时间序列的建模方式
2022-08-31 03:35:30
![](https://img.aspxhome.com/file/2023/4/131084_0s.jpg)
Go读取文件与写入文件的三种方法操作指南
2024-02-01 05:29:46
python机器学习包mlxtend的安装和配置详解
2021-11-09 22:53:06
![](https://img.aspxhome.com/file/2023/3/135373_0s.png)
Python socket如何解析HTTP请求内容
2022-05-06 20:09:23
z-blog文章摘要图文混排
2009-02-28 13:49:00
![](https://img.aspxhome.com/file/UploadPic/20092/28/tagimg-64s.gif)
YOLOv5目标检测之anchor设定
2022-04-23 16:22:10
![](https://img.aspxhome.com/file/2023/9/87809_0s.jpg)
Python中使用zip函数的七重境界解析
2021-04-01 19:38:43
用Python做的数学四则运算_算术口算练习程序(后添加减乘除)
2023-04-10 13:27:35
pandas 添加空列并赋空值案例
2022-12-04 13:48:16
![](https://img.aspxhome.com/file/2023/1/72091_0s.jpg)
Pygame实战练习之保护单身狗游戏
2022-07-04 03:30:28
![](https://img.aspxhome.com/file/2023/5/94135_0s.gif)
Python3利用print输出带颜色的彩色字体示例代码
2022-09-08 07:53:29
![](https://img.aspxhome.com/file/2023/0/104390_0s.jpg)
Linux下mysql 8.0安装教程
2024-01-15 18:21:49
![](https://img.aspxhome.com/file/2023/5/68595_0s.jpg)