可以通過toString()
來獲取每個對象的類型。爲了每個對象都能通過 Object.prototype.toString()
來檢測,需要以 Function.prototype.call()
或者 Function.prototype.apply()
的形式來調用,傳遞要檢查的對象作爲第一個參數,稱爲thisArg
。
var toString = Object.prototype.toString;
toString.call(undefined); // "[object Undefined]"
toString.call(null); // "[object Null]"
toString.call(new String); // "[object String]"
toString.call("abc"); // "[object String]"
toString.call(new Number); // "[object Number]"
toString.call(123); // "[object Number]"
toString.call(new Array); // "[object Array]"
toString.call([1,2,3]); // "[object Array]"
toString.call(new Boolean); // "[object Boolean]"
toString.call(true); // "[object Boolean]"
toString.call(new Object); // "[object Object]"
toString.call({a: 1, b: 2}); // "[object Object]"
toString.call(new Function); // "[object Function]"
toString.call(function(x){ return x * x; }); // "[object Function]"
toString.call(Math); // "[object Math]"
toString.call(new Date); // "[object Date]"
下面提供一個獲取所有類型的方法:
function getType(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
getType(undefined); // "Undefined"
getType(null); // "Null"
getType("abc"); // "String"
getType(123); // "Number"
getType([1,2,3]); // "Array"
getType(true); // "Boolean"
getType({a: 1, b: 2}); // "Object"
getType(function(x){ return x * x; }); // "Function"
getType(Math); // "Math"
getType(new Date); // "Date"