JS中判断null、undefined与NaN的方法

时间:2024-04-19 09:54:05 

写了个 str ="s"++;
然后出现Nan,找了一会。
收集资料如下判断:
1.判断undefined:


<span style="font-size: small;">var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}</span>


说明:typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"
2.判断null:


<span style="font-size: small;">var tmp = null;
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){
alert("null");
}</span>


3.判断NaN:


<span style="font-size: small;">var tmp = 0/0;
if(isNaN(tmp)){
alert("NaN");
}</span>


说明:如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符。
提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。
4.判断undefined和null:


<span style="font-size: small;">var tmp = undefined;
if (tmp== undefined)
{
alert("null or undefined");
} </span>



<span style="font-size: small;">var tmp = undefined;
if (tmp== null)
{
alert("null or undefined");
}</span>


说明:null==undefined
<!--EndFragment-->
5.判断undefined、null与NaN:


<span style="font-size: small;">var tmp = null;
if (!tmp)
{
alert("null or undefined or NaN");
}</span>


提示:一般不那么区分就使用这个足够。

标签:null,undefined,NaN
0
投稿

猜你喜欢

  • python使用正则表达式匹配字符串开头并打印示例

    2021-07-02 00:52:13
  • mac os10.12安装mysql5.7.18教程

    2024-01-19 14:08:27
  • python作图基础之plt.contour实例详解

    2023-04-05 01:05:44
  • python 判断文件或文件夹是否存在

    2021-06-30 05:56:55
  • 配置python的编程环境之Anaconda + VSCode的教程

    2021-09-05 14:12:18
  • 安装PHP可能遇到的问题“无法载入mysql扩展” 的解决方法

    2023-09-09 04:37:39
  • php判断用户是否关注微信公众号

    2024-04-28 09:45:25
  • Python机器学习应用之基于天气数据集的XGBoost分类篇解读

    2023-09-12 05:45:07
  • Tornado Web服务器多进程启动的2个方法

    2022-01-21 04:41:05
  • Python开发微信公众平台的方法详解【基于weixin-knife】

    2023-03-09 12:05:43
  • 详解通过API管理或定制开发ECS实例

    2022-11-02 17:44:00
  • 关于vue父组件调用子组件的方法

    2024-04-09 10:47:43
  • 基于Python代码编辑器的选用(详解)

    2022-08-13 23:44:39
  • Python使用grequests并发发送请求的示例

    2022-11-08 15:38:01
  • python通过nmap扫描在线设备并尝试AAA登录(实例代码)

    2021-08-06 23:23:42
  • 将tensorflow.Variable中的某些元素取出组成一个新的矩阵示例

    2022-01-17 23:49:50
  • golang判断net.Conn 是否已关闭的操作

    2024-04-30 10:07:02
  • python枚举类型定义与使用讲解

    2021-04-11 08:55:42
  • python的语句结构你真的了解吗

    2022-08-11 23:05:39
  • JavaScript高级程序设计(第3版)学习笔记2 js基础语法

    2024-06-07 15:59:19
  • asp之家 网络编程 m.aspxhome.com