在 JavaScript 里使用 typeof 來判斷數據類型,只能區分基本類型,即 “number”,”string”,”undefined”,”boolean”,”object” 五種。對于數組、函數、對象來說,其關系錯綜復雜,使用 typeof 都會統一返回 “object” 字符串。
要想區別對象、數組、函數單純使用 typeof 是不行的。或者你會想到 instanceof 方法,例如下面這樣:
var a = {};
var b = [];
var c = function () {};
//a b c 都是 Object 的實例
console.log(a instanceof Object) //true
console.log(b instanceof Object) //true
console.log(c instanceof Object) //true
//只有 Array 類型的 b 才是 Array 的實例
console.log(a instanceof Array) //false
console.log(b instanceof Array) //true
console.log(c instanceof Array) //false
//只有 Function 類型的 c 才是 Function 的實例
console.log(a instanceof Function) //false
console.log(b instanceof Function) //false
console.log(c instanceof Function) //true
從以上代碼來看,要判斷復合數據類型,可以如下判斷:
//對象
(a instanceof Object) && !(a instanceof Function) && !(a instanceof Function)
//數組
(a instanceof Object) && (a instanceof Array)
//函數
(a instanceof Object) && (a instanceof Function)
更簡便的方式,即是使用 Object.prototype.toString.call() 來確定類型,ECMA 5.1 中關于該方法的描述[1]是這樣的:
When the toString method is called, the following steps are taken:
If the this value is undefined, return “[object Undefined]“.
If the this value is null, return “[object Null]“.
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings “[object ", class, and "]“.
由于 JavaScript 中一切都是對象,任何都不例外,對所有值類型應用 Object.prototype.toString.call() 方法結果如下:
console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]
所有類型都會得到不同的字符串,幾乎完美。