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

相关文章
相关标签/搜索