JavaScript类型检测

     在编写JS代码中,经常要对某个变量进行类型检测。常用的类型检测方法有:

  • typeof
  • Object.prototype.toString
  • constructor
  • instanceof

typeof

typeof可以识别出基本数据类型(null除外),同时typeof并不能识别具体的对象类型(Function除外).

eg:   

typeof "seven";     // "string"
typeof 7;     //"number"
typeof true ;     // "boolean"
typeof undefined;  // "undefined"
typeof null   ;       // "object"    
typeof {name:"seven"};   //"object"
typeof function(){};    //"function"
typeof [] ;    //"object"
typeof new Date;   //"object"
typeof /\w/ ;    // "object"
function Student(){};
typeof   new Student(); //"object"

 

Object.prototype.toString

在任何值上调用Object原生的toString()方法,都会返回一个[object NativeConstructorName]格式的字符串。

NativeConstructorName即为构造函数名。

例如:

console.log(Object.prototype.toString.call({})); // "[object Object]"
console.log(Object.prototype.toString.call([])); // "[object Array]"

  

 

所以Object.prototype.toString能够区分出如Array,RegExp,Function,Date等内置对象类型。

因此可以封装一个方法:

function type(param){
    return Object.prototype.toString.call(param).slice(8,-1);  
}

该方法能直接返回传入参数的类型。

console.log(type([])); // "Array"
console.log(new Date()); // "Date"
console.log(null); // "Null"
console.log(1); // "Number"

function Person(name){
     this.name = name;
}

var seven = new Person('seven');

type(seven);   //"Object"

总结:  

可以识别出内置对象类型(Array,Function,RegExp等)和标准类型(null,undefined,number,boolean,string)

不能识别出自定义类型(都返回"Object")

 

 

 

 

 

 

 

 

posted @ 2015-05-27 21:26  kiliro  阅读(129)  评论(0)    收藏  举报