这里参考了jQuery的做法:
var class2type={}; //定义一个对象
var typeArr = "Boolean Number String Function Array Date RegExp Object".split(" ");//将所有的类型放到一个数组
for(var i=0,len=typeArr.length;i<len;i++){
var name=typeArr[i];
class2type[ "[object " + name + "]" ] = name;
}
function getType( obj ) {
return obj == null ?
String( obj ) :
class2type[ Object.prototype.toString.call(obj) ] || "undefined";
}
console.log(getType("abc"));//字符串String
console.log(getType(1));//数字Number
console.log(getType(null));//null
console.log(getType(undefined));//undefined
console.log(getType(function(){}));//Function
console.log(getType({}));//Object
console.log(getType(/test/));//RegExp
console.log(getType(true));//Boolean
console.log(getType([]));//Array
console.log(getType(new Date()));//Date
输出:
String
Number
null
undefined
Function
Object
RegExp
Boolean
Array
Date
用这个来判断类型的话,就一目了然。
把typeof输出放到一起,来比对一下就很明显了:
console.log(getType("abc"),"----",typeof "abc");//字符串String
console.log(getType(1),"----",typeof 1);//数字Number
console.log(getType(true),"----",typeof true);//Boolean
console.log(getType(function(){}),"----",typeof function(){});//Function
console.log(getType(null),"----",typeof null);//null
console.log(getType(undefined),"----",typeof undefined);//undefined
console.log(getType({}),"----",typeof {});//Object
console.log(getType(/test/),"----",typeof /test/);//RegExp
console.log(getType([]),"----",typeof []);//Array
console.log(getType(new Date()),"----",typeof new Date());//Date
看输出结果的比较:
String ---- string
Number ---- number
Boolean ---- boolean
Function ---- function
null ---- object
undefined ---- undefined
Object ---- object
RegExp ---- object
Array ---- object
Date ---- object
看结果typeof有几个判断为object的,而封装后却能明显的区分开来!