先看一段實測程式碼,把三種常見手段跑出來比一比:
var a = ['hello','world']; console.log(typeof a); // object console.log(a.toString()); // hello,word 字符串 console.log(Object.prototype.toString.call(a)); //[object Array] var b = {'hello':'world'}; console.log(typeof b); // object console.log(b.toString()); // [object Object] console.log(Object.prototype.toString.call(b));// [object Object]
結論可以濃縮成三句話:
1. Array 與 Object 用 typeof 判斷,結果都是 object,完全分不出來。
2. 呼叫 toString() 時,Array 會回傳真正的內容字串(例如 hello,world),Object 則固定回傳 [object Object]。
3. 改用 Object.prototype.toString.call(),Array 會穩定回傳 [object Array],Object 依然是 [object Object]。
console.log( Array.isArray(a) ); // true console.log( Array.isArray(b) ); // false
三個方案各有取捨:toString() 看似可用,但一旦陣列元素剛好長得像標籤字串就容易誤判,不建議當成正式判斷;Object.prototype.toString.call 通用性最好,跨 iframe 也不受影響;Array.isArray 語意最清楚,是目前的正確答案,只需要留意非常舊的瀏覽器不支援即可。