码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript的typeof操作符与数据类型

时间:2014-12-03 11:57:25      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

typeof 操作符:typeof 操作符是用来检测变量的数据类型。对于值或变量使用 typeof 操作符会返回如下字符串。

bubuko.com,布布扣

bubuko.com,布布扣
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 5 <title>数据类型</title>
 6 <script type="text/javascript">
 7 /*
 8     var box;
 9     alert(box);//undefined
10     alert(typeof box);//box是Undefined类型,值是undefined,类型返回的字符串也是undefined
11 
12     
13     var boxBoolean = true;
14     alert(boxBoolean);//true
15     alert(typeof boxBoolean);//boxBoolean是Boolean类型,值是true,类型返回的字符串也是boolean
16 
17     
18     var boxString = ‘奥巴马‘;
19     alert(boxString);//奥巴马
20     alert(typeof boxString);//boxString是String类型,值是‘奥巴马‘,类型返回的字符串也是string
21 
22     var boxNumber = 100;
23     alert(boxNumber);//100
24     alert(typeof boxNumber);//boxNumber是Number类型,值是100,类型返回的字符串也是number
25 
26     //空的对象,表示这个对象创建了,但里面没有东西
27     //空对象,表示没有创建,就是一个null
28     var boxObject = {};//创建了一个空的对象
29     alert(boxObject);//[object Object]
30     alert(typeof boxObject);//boxObject是Object类型,值是[object Object],类型返回的字符串也是object
31     
32     var boxObject = new Object();//创建了一个空的对象
33     alert(boxObject);//[object Object]
34     alert(typeof boxObject);//boxObject是Object类型,值是[object Object],类型返回的字符串也是object
35 
36     var boxNull = null;
37     alert(boxNull);//null 或者什么都没有只有一个窗口
38     alert(typeof boxNull);//boxNull是null类型,值是null或者什么都没有,类型返回的字符串也是object
39     
40 
41     function boxFunction(){
42         
43     }
44     alert(boxFunction);//打印出本体
45     alert(typeof boxFunction);//boxFunction是Function函数 值是本体function boxFunction(){},类型返回的字符串是function
46 */
47     //可以直接对值(字面量)用typeof
48     alert(typeof 奥巴马);//string
49 </script>
50 </head>
51 
52 <body>
53 欢迎来到javascript的世界
54 </body>
55 </html>
bubuko.com,布布扣

typeof 操作符可以操作变量,也可以操作字面量。虽然也可以这样使用:typeof(box),但,typeof 是操作符而非内置函数。PS:函数在 ECMAScript 中是对象,不是一种数据类型。所以,使用 typeof 来区分 function 和 object 是非常有必要的。


数据类型,布布扣,bubuko.com

JavaScript的typeof操作符与数据类型

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/LO-ME/p/3577211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!