JavaScript中使用Object.prototype.toString判斷是否為數(shù)組

字號:


    為什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?這是和他們的toString解釋方式有關(guān)系的。下面是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)
    其過程簡單說來就是:1、獲取對象的類名(對象類型)。2、然后將[object、獲取的類名、]組合并返回。
    ECMA中對Array有如下說明:
    代碼如下:
    The [[Class]] property of the newly constructed object is set to “Array”.
    因此我們用如下代碼來檢測數(shù)組:
    代碼如下:
    function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; }
    這種方式既解決了instanceof存在的跨頁面問題,也解決了屬性檢測方式所存在的問題,實在是一種妙招,一個很好的解決方案。
    除此之外,這種解決辦法也可以應(yīng)用于判斷Date,Function等類型的對象。
    另外還有幾個方法:
    代碼如下:
    var arr = []; return arr instanceof Array;
    如果有其他好的方法不妨貼出來。