javascript一共有6種數(shù)據(jù)類型怠硼,其中包含5種基本類型:Undefined鬼贱、Null、Boolean香璃、Number这难、String,和一中復雜類型Object葡秒。在實際運用中姻乓,有時需要判斷是什么類型,判斷是否符合要求或根據(jù)不同的類型做出不同的類型眯牧。
一蹋岩、typeof操作符 — 用于識別正在處理的對象的類型
這個操作符可能返回"undefined"、"boolean"炸站、"number"星澳、"string"、"object"旱易、"function"
<b>注意:typeof(null) == "object"禁偎,null被當做是一個空對象。對正則表達式調(diào)用typeof,safari5及以前的版本阀坏、chrome7及以前的版本會返回"function"如暖,其他瀏覽器會返回"object"。</b>
二忌堂、instanceof — 用于判斷一個變量是否某個對象的實例
typeof是檢測基本類型的得力助手盒至,而instanceof適合檢測引用類型。
variable instanceof Object ,如果是引用類型都返回true,如果是基本類型都返回false士修。
instanceof可以檢測Object枷遂、Function、Array棋嘲、RegExp等酒唉。
三、常用應用場景
(一)檢測數(shù)組沸移、對象
1.all改變toString的this引用為待檢測的對象
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
ECMA-262 寫道
Object.prototype.toString( ) When the toString method is called, the following steps are taken:
- Get the [[Class]] property of this object.
- Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
- Return Result (2)
上面的規(guī)范定義了Object.prototype.toString的行為:首先痪伦,取得對象的一個內(nèi)部屬性[[Class]]侄榴,然后依據(jù)這個屬性,返回一個類似于"[object Array]"的字符串作為結果(看過ECMA標準的應該都知道网沾,[[]]用來表示語言內(nèi)部用到的癞蚕、外部不可直接訪問的屬性,稱為“內(nèi)部屬性”)辉哥。利用這個方法桦山,再配合call,我們可以取得任何對象的內(nèi)部屬性[[Class]]证薇,然后把類型檢測轉化為字符串比較度苔,以達到我們的目的。還是先來看看在ECMA標準中Array的描述吧:
ECMA-262 寫道
new Array([ item0[, item1 [,…]]])
The [[Class]] property of the newly constructed object is set to “Array”.
于是利用這點浑度,第三種方法登場了寇窑。
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
} call改變toString的this引用為待檢測的對象,返回此對象的字符串表示箩张,然后對比此字符串是否是'[object Array]'甩骏,以判斷其是否是Array的實例。也許你要問了先慷,為什么不直接o.toString()饮笛?嗯,雖然Array繼承自Object论熙,也會有toString方法福青,但是這個方法有可能會被改寫而達不到我們的要求,而Object.prototype則是老虎的屁股脓诡,很少有人敢去碰它的无午,所以能一定程度保證其“純潔性”:)
這個方法很好的解決了跨frame對象構建的問題,經(jīng)過測試祝谚,各大瀏覽器兼容性也很好宪迟,可以放心使用。一個好消息是交惯,很多框架次泽,比如jQuery、Base2等等席爽,都計劃借鑒此方法以實現(xiàn)某些特殊的意荤,比如數(shù)組、正則表達式等對象的類型判定只锻,不用我們自己寫了玖像。
2.使用typeof加length屬性
var arr = [1,2,3,4,5];var obj = {};
function getDataType(o){
if(typeof o == 'object'){
if( typeof o.length == 'number' ){
return 'Array';
}else{
return 'Object';
}
}else{
return 'param is no object type';
}
}
3.使用instanceof
function getDataType(){
if(o instanceof Array){
return 'Array';
}else if( o instanceof Object ){
return 'Object';
}else{
return 'param is no object type';
}
}
這個方法在iframe中會有問題
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray("1","2","3","4","5");//這個寫法IE大哥下是不支持的,F(xiàn)F下才有
alert(arr instanceof Array); // false
alert(arr.constructor === Array); // false