常见的伪数组是由元素获取的到的如:document.getElementsByTagName(‘li’)
数组于伪数组的差别有不具有数组所具有的方法和伪数组的length属性是静态的不可变
分辨
1.console.log打印出来
可以打印出来分辨:
真数组:
伪数组:
或者__proto__是object;总之不是Array
2.Array.isArray()
这个方法可以判断该对象是不是数组。是数组就返回true,不是数组就返回false
Array.isArray(arr)
3.Object.prototype.toString.call(arr)
这个方法可以精确判断对象的类型;
之前常用的typeof 并不能判断伪数组:
都返回object;
但是Object.prototype.toString.call(arr):
能返回准确的类型;
4.使用数组的方法
伪数组不是数组他只是有数组的属性但不能使用数组的方法所以其实可以使用这个特性来判断比如:
伪数组使用数组的方法就会报错;
5.《javascript权威指南》上给出了代码用来判断一个对象是否属于“伪数组
function isArrayLike(o){
if(o && //o非null.undefined
typeof o === "object" && //o是对象
isFinite(o.length) && //o.length是有限数值
o.length > 0 && //o.length为非负数
o.length === Math.floor(o.length) && //o.length是整数
o.length < 4294967296 ){
//o.length<2^32
return true;
}else{
return false;
}
}