JavaScript判断一个变量是对象还是数组

本文介绍两种方法来区分JavaScript中的对象与数组:利用length属性结合typeof操作符,及使用instanceof关键字。确保准确判断数据类型。

JavaScript判断一个变量是对象还是数组

typeof都返回object

在JavaScript中所有数据类型严格意义上都是对象,但实际使用中我们还是有类型之分,如果要判断一个变量是数组还是对象使用typeof搞不定,因为它全都返回object

1
2
3
4
5
6
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);

执行:

o typeof is object
a typeof is object   

因此,我们只能放弃这种方法,要判断是数组or对象有两种方法

第一,使用typeof加length属性

数组有length属性,object没有,而typeof数组与对象都返回object,所以我们可以这么判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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可以判断一个变量是不是数组,如:

1
2
3
4
5
var o = { 'name':'lee' };
var a = ['reg','blue'];
 
alert( a instanceof Array );  // true
alert( o instanceof Array );  // false

也可以判断是不是属于object

1
2
3
4
5
var o = { 'name':'lee' };
var a = ['reg','blue'];
 
alert( a instanceof Object );  // true
alert( o instanceof Object );  // true

但数组也是属于object,所以以上两个都是true,因此我们要利用instanceof判断数据类型是对象还是数组时应该优先判断array,最后判断object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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,比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值