js 判断数据类型之typeof

typeof [ ( ] expression [ ) ] ;   // expression 参数是需要查找类型信息的任意表达式。  typeof 语法中的圆括号是可选项。 

typeof 运算符返回一个用来表示表达式的数据类型的字符串。即: typeof 运算符把类型信息当作字符串返回
可能的字符串有六种:"string"、"number"、"boolean"、"object"、"function" 和 "undefined"。 
如: 
alert(typeof (123));//typeof(123)返回"number" 
alert(typeof ("123"));//typeof("123")返回"string"

我们可以使用typeof来获取一个变量是否存在
如 : if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错

运算数为数字 typeof(x) = “number”

字符串 typeof(x) = “string”

布尔值 typeof(x) = “boolean”

对象,数组和null typeof(x) = “object”

函数 typeof(x) = “function”

对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

使用typeof操作符

对一个值使用typeof操作符可能返回下列某个字符串:

1):undefined——如果这个值未定义

2):boolean——如果这个值是布尔值

3):string——如果这个值是字符串

4):number——如果这个值是数值

5):object——如果这个值是对象或null

6):function——如果这个值是函数 

 

值得注意的是:typeof是操作符而不是函数,因此圆括号尽管可以使用,但不是必须的

为了区分对象的类型,我们用typeof操作符获取对象的类型,它总是返回一个字符串:

 

typeof 123; // 'number'
typeof NaN; // 'number'
typeof 'str'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof Math.abs; // 'function'
typeof null; // 'object'
typeof []; // 'object'
typeof {}; // 'object'

可见,numberstringbooleanfunctionundefined有别于其他类型。

特别注意null的类型是objectArray的类型也是object,如果我们用typeof将无法区分出nullArray和通常意义上的object——{}

  • 判断Array要使用Array.isArray(arr)

  • 判断null请使用myVar === null

    • 判断某个全局变量是否存在用typeof window.myVar === 'undefined'

    • 函数内部判断某个变量是否存在用typeof myVar === 'undefined'



instanceof
如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。instanceof用于判断一个变量是否某个对象的实例:

如var a=new Array();
    alert(a instanceof Array); // 会返回true
同时alert(a instanceof Object); // 也会返回true;  这是因为Array是object的子类。
再如:function test(){};
           var a=new test();
         alert(a instanceof test) ; // 会返回true。

友情提示

a instanceof Object 得到true并不是因为 Array是Object的子对象,而是因为 Array的prototype属性构造于Object,Array的父级是Function

 

posted @ 2016-04-18 13:19  蝴蝶女郎  阅读(211)  评论(0)    收藏  举报