JavaScript中使用Object.prototype.toString判斷是否為數(shù)組
來源:易賢網(wǎng) 閱讀:1207 次 日期:2015-04-02 16:24:29
溫馨提示:易賢網(wǎng)小編為您整理了“JavaScript中使用Object.prototype.toString判斷是否為數(shù)組”,方便廣大網(wǎng)友查閱!

為什么要用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存在的跨頁面問題,也解決了屬性檢測方式所存在的問題,實在是一種妙招,一個很好的解決方案。

除此之外,這種解決辦法也可以應用于判斷Date,Function等類型的對象。

另外還有幾個方法:

代碼如下:

var arr = []; return arr instanceof Array;

如果有其他好的方法不妨貼出來。

更多信息請查看IT技術(shù)專欄

更多信息請查看腳本欄目
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點

版權(quán)所有:易賢網(wǎng)