判断是否是数组的几种方法

判断objectName是否是数组

1、objectName instanceof Array

2、objectName.constructor == Array

基本数据类型也可以使用此方法。

(123).constructor == Number // true
  • 1

1、2判断有误差。 
a)在不同 iframe 中创建的 Array 并不共享 prototype 
b)即使为true,也有可能不是数组。 
function SubArray(){ 

SubArray.prototype = []; 
myArray = new SubArray; 
alert(myArray instanceof Array)

3、特性判断

a)length 
b)splice 
c)length不可枚举

    function isArray(object){
    return  object && typeof object==='object' &&    
            typeof object.length==='number' &&  
            typeof object.splice==='function' &&    
             //判断length属性是否是可枚举的 对于数组 将得到false  
            !(object.propertyIsEnumerable('length'));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

有length和splice并不一定是数组,因为可以为对象添加属性,而不能枚举length属性,才是最重要的判断因子。

4、Array.isArray(objectName);

ES5方法

5、Object.prototype.toString.call(objectName)

获取this对象的[[Class]]属性的值.[Class]]是一个内部属性,所有的对象都拥有该属性. 表明该对象的类型 
Object.prototype.toString.call(objectName) === ‘[object Array]‘;

猜你喜欢

转载自blog.csdn.net/aaa333qwe/article/details/80331153