javascript中typeof的用法

来源:互联网 发布:hl绘图编程怎么取轨迹 编辑:程序博客网 时间:2024/05/16 15:20

 typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。它返回值是一个字符串,该字符串说明运算数的类型。


具体的规则如下:
1、对于数字类型的操作数而言, typeof 返回的值是 number。比如说:typeof(1),返回的值就是number。
上面是举的常规数字,对于非常规的数字类型而言,其结果返回的也是number。比如typeof(NaN),NaN在
JavaScript中代表的是特殊非数字值,虽然它本身是一个数字类型。
在JavaScript中,特殊的数字类型还有几种:
Infinity 表示无穷大特殊值
NaN            特殊的非数字值
Number.MAX_VALUE     可表示的最大数字
Number.MIN_VALUE     可表示的最小数字(与零最接近)
Number.NaN        特殊的非数字值
Number.POSITIVE_INFINITY 表示正无穷大的特殊值
Number.NEGATIVE_INFINITY  表示负无穷大的特殊值

以上特殊类型,在用typeof进行运算进,其结果都将是number。

2、对于字符串类型, typeof 返回的值是 string。比如typeof("123")返回的值是string。 
3、对于布尔类型, typeof 返回的值是 boolean 。比如typeof(true)返回的值是boolean。
4、对于对象、数组、null 返回的值是 object 。比如typeof(window),typeof(document),typeof(null)返回的值都是object。
5、对于函数类型,返回的值是 function。比如:typeof(eval),typeof(Date)返回的值都是function。
6、如果运算数是没有定义的(比如说不存在的变量、函数或者undefined),将返回undefined。比如:typeof(sss)、typeof(undefined)都返回undefined。


typeof后面的括号可以缺省,比如typeof 123和typeof(123)的写法是等同的。


举例:

<script>function person(firstname,lastname,age,eyecolor){this.firstname=firstname;this.lastname=lastname;this.age=age;this.eyecolor=eyecolor;this.getName = function(){           return "LiLei"; }}var p = new person();var arr = ["123", "456"];document.write(typeof 123);//typeof(123)返回"number" document.write("<br/>");document.write(typeof(NaN));//typeof(123)返回"number" document.write("<br/>");document.write(typeof("123"));//typeof("123")返回"string"document.write("<br/>");document.write(typeof(x));//未定义变量,typeof(x)返回undefineddocument.write("<br/>");document.write(typeof(person));//typeof(person)返回"function"document.write("<br/>");document.write(typeof (p));//typeof(new person())返回"object"document.write("<br/>");document.write(typeof null);//typeof(null)返回"object"document.write("<br/>");document.write(typeof(arr));//typeof(arr)返回"object"document.write("<br/>");document.write(typeof(p.getName()));//typeof(arr)返回"string"document.write("<br/>");document.write(typeof(p.getName));//typeof(arr)返回"function"document.write("<br/>");</script>

执行结果如下:

numbernumberstringundefinedfunctionobjectobjectobjectstringfunction

0 0
原创粉丝点击