Common pseudo-arrays are obtained by elements such as: document.getElementsByTagName('li')
The difference between an array and a pseudo-array is that it does not have the methods that an array has and the length property of the pseudo-array is static and immutable.
Distinguish
1. The console.log is printed out. It
can be printed out to distinguish:
true array:
pseudo array:
Or __proto__ is an object; in short, it is not an Array
2. Array.isArray()
This method can determine whether the object is an array. Return true if it is an array, false if it is not an array
Array.isArray(arr)
3. Object.prototype.toString.call(arr)
This method can accurately determine the type of the object; the
commonly used typeof before cannot determine the pseudo-array:
Both return object;
but Object.prototype.toString.call(arr):
can return the exact type;
4. The method of using arrays.
Pseudo-arrays are not arrays. They just have the attributes of arrays but cannot use arrays. So you can actually use this feature to judge
.
5. "JavaScript Authoritative Guide" gives the code to determine whether an object belongs to a "pseudo array"
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;
}
}