JavaScript用typeof判断变量是数组还是对象,都返回object

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

使用typeof加length属性

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

  1. var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];

             shopping;

  • typeof shopping;
    "object"

  • var getDataType = function(shopping){
    if(typeof shopping == 'object'){
    if( typeof shopping.length == 'number' ){
    return 'Array';
    }else{
    return 'Object';
    }
    }else{
    return 'param is no object type';
    }
    };
    alert( getDataType(shopping) );

原文链接:http://www.qttc.net/201306338.html

原文地址:https://www.cnblogs.com/wubuwei/p/7196183.html