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

本文阅读 1 分钟
首页 › 前端笔记 › 正文

typeof 都返回 object

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

第一,使用 typeof 加 length 属性

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

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';
    }
};

第二,使用 instanceof

利用 instanceof 判断数据类型是对象还是数组时应该优先判断 array,最后判断 object。

var getDataType = function(o){
    if(o instanceof Array){
        return 'Array'
    } else if ( o instanceof Object ){
        return 'Object';
    } else {
        return 'param is no object type';
    }
};
闭包的理解 ?
« 上一篇 03-12
升职加薪30天训练营(完结)
下一篇 » 03-31

发表评论