判斷一個對象是否為數組,看似簡單,實則暗藏玄機。本文詳細說明為何 Object.prototype.toString 是最可靠的方案之一,並解讀其背後的原理。
先說為什麼用它,而不是 Function.prototype.toString 或其他。這與它們的 toString 解釋方式有關。ECMA 對 Object.prototype.toString 的定義是:
代碼如下:
Object.prototype.toString( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings "[object ", Result (1), and "]".
3. Return Result (2)
通俗地說:先獲取對象的內部 [[Class]] 屬性(即類型標識),再把 "[object"、類型名、"]" 拼接返回。
而 ECMA 對 Array 的說明是:
代碼如下:
The [[Class]] property of the newly constructed object is set to "Array".
於是我們就能用它來檢測數組:
代碼如下:
function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; }
這種方式既解決了 instanceof 的跨頁面(跨 iframe)問題,也避免了屬性檢測方式的各種坑,可謂一舉兩得。除此之外,同樣的手法還能用來判斷 Date、Function 等類型。
當然,還有其他方案:
代碼如下:
var arr = []; return arr instanceof Array;
總的來說,在需要兼顧準確性與兼容性的場景下,Object.prototype.toString.call() 是一個值得信賴的選擇;而在現代環境中,也可直接採用 Array.isArray()。