js判斷一個變量是對象仍是數組

引用原網址  http://www.111cn.net/wy/js-ajax/49504.htmajax

 

typeof都返回object數組

在JavaScript中全部數據類型嚴格意義上都是對象,但實際使用中咱們仍是有類型之分,若是要判斷一個變量是數組仍是對象使用typeof搞不定,由於它全都返回objectspa

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
document.write( ' o typeof is ' + typeof o);
document.write( ' <br />');
document.write( ' a typeof is ' + typeof a);
2 執行:
3 o typeof is object
a typeof is object  

所以,咱們只能放棄這種方法,要判斷是數組or對象有兩種方法.net

第一,使用typeof加length屬性
數組有length屬性,object沒有,而typeof數組與對象都返回object,因此咱們能夠這麼判斷code

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
var getDataType = function(o){
    if(typeof o == 'object'){
        if( typeof o.length == 'number' ){
            return 'Array'; 
        }else{
            return 'Object';    
        }
    }else{
        return 'param is no object type';
    }
};
 
alert( getDataType(o) );    // Object
alert( getDataType(a) );    // Array
alert( getDataType(1) );    // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );  // param is no object type

第二,使用instanceof
使用instanceof能夠判斷一個變量是否是數組,如:htm

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
alert( a instanceof Array );  // true
alert( o instanceof Array );  // false

也能夠判斷是否是屬於object對象

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
alert( a instanceof Object );  // true
alert( o instanceof Object );  // true

但數組也是屬於object,因此以上兩個都是true,所以咱們要利用instanceof判斷數據類型是對象仍是數組時應該優先判斷array,最後判斷objectip

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
var getDataType = function(o){
    if(o instanceof Array){
        return 'Array'
    }else if( o instanceof Object ){
        return 'Object';
    }else{
        return 'param is no object type';
    }
};
 
alert( getDataType(o) );    // Object
alert( getDataType(a) );    // Array
alert( getDataType(1) );    // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );  // param is no object type

若是你不優先判斷Array,好比:ci

 代碼以下
1 var o = { 'name':'lee' };
var a = ['reg','blue'];
 
var getDataType = function(o){
    if(o instanceof Object){
        return 'Object'
    }else if( o instanceof Array ){
        return 'Array';
    }else{
        return 'param is no object type';
    }
};
 
alert( getDataType(o) );    // Object
alert( getDataType(a) );    // Object
alert( getDataType(1) );    // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') );  // param is no object type

那麼數組也會被判斷爲object。get

相關文章
相關標籤/搜索