欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

(转载)Javascript 中的非空判断 undefined,null, NaN的区别

程序员文章站 2022-07-26 19:05:59
原文地址:https://blog.csdn.net/oscar999/article/details/9353713 在介绍这三个之间的差别之前, 先来看一下JS 的数据类型。 在 Java ,C这样的语言中, 使用一个变量之前,需要先定义这个变量并指定它的数据类型,是整型,字符串型,.... 但 ......

原文地址:

在介绍这三个之间的差别之前, 先来看一下js  的数据类型。

在 java ,c这样的语言中, 使用一个变量之前,需要先定义这个变量并指定它的数据类型,是整型,字符串型,....

但是在js 中定义变量统一使用 var , 或者不使用var 也可以使用。

那么js 中是否有数据类型的概念呢? 当然有, 使用 typeof 就可以判断这个变量的数据类型:

<!--add by oscar999-->
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> new document </title>
<meta name="author" content="oscar999">
<script>
s = "this is test";
alert(typeof(s));
</script>
</head>
 
<body>
 
</body>
</html>

以上例子弹出的值是 "string", 由此可以看出, js 也是有数据类型的。
js中的数据类型有undefined,boolean,number,string,object等5种,前4种为原始类型,第5种为引用类型。

原始类型和引用类型有什么区别?引用的概念其他语言的引用很类似, 就是一个地址。看一下这个例子就知道了。

<!--add by oscar999-->
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> new document </title>
<meta name="author" content="oscar999">
<script>
var obj = new object();
var objcopy = obj;
obj.att1 = "obj attribute";
alert(objcopy.att1);
</script>
</head>

<body>

</body>
</html>

别忽略了object 类型的这种特性哦, 这个是会被经常误用的地方。类似上面的obj的改变引起了objcopy的改变。
除了以上5 中类型之外, 还有一种 “function”的类型。

<!--add by oscar999-->
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> new document </title>
<meta name="author" content="oscar999">
<script>
function test()
{
alert("hello");
}
alert(typeof(test));
</script>
</head>

<body>

</body>
</html>

 undefined 和 null, nan 的区别
有了上面的介绍,就可以很容易把undefined 和其他的两个区分开来。

undefined判断的是变量的类型,而其他两个判断是变量的值。

undefined可以用来表示以下的状况

1. 表示一个未声明的变量,

2. 已声明但没有赋值的变量,

3. 一个并不存在的对象属性

 

null 是一种特殊的object ,表示无值;

nan是一种特殊的number ,表示无值;

 

比较符(== 或 ===)
使用 == ,如果两边的类型不同, js 引擎会先把它们转成相同的类型在进行值的比较;

使用 ===, 则不会进行类型转换,类型不同,肯定不相等。 

 

实例
有了以上的知识,再来看下面一些有意思却容易混淆的例子应该就很清晰了:

<!--add by oscar999-->
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> new document </title>
<meta name="author" content="oscar999">
<script>
var s;
alert(s==undefined); //true
alert(s===undefined); //true

alert(s==null); //true
alert(s===null); //false

alert(null==undefined); //true
alert(null===undefined); //false
</script>
</head>

<body>

</body>
</html>

把var s 改成 var s = null 再看看效果~~


一般情况下, 对js 某个变量s 判空习惯使用 if(s!=null) , 如果s 没有定义的话,就会报undefined的js 错误, 所以完整的判空可以使用如下方式:

if(typeof(s)!="undefined"&&s!=null)