Strings and functions have a length property, but they can be excluded by typeof detection. In client-side Js, DOM text nodes also have a length attribute, which requires additional judgment obj.nodeType != 3 to exclude it (the nodeType attribute returns the node type of the specified node as a numeric value. If the node is an element node, the nodeType attribute will return 1. If the node is a property node, the nodeType property will return 2):
// 判定obj是否是一个类数组对象
function isArrayLike( obj ) {
if( obj && typeof obj === "object" && // obj非null、undefined等 obj是对象
isFinite(obj.length) && // obj.length是有限数值
obj.length >= 0 && // obj.length为非负数
obj.length === Math.floor(obj.length) && // obj.length是整数
obj.length < 4294967296) // obj.length < 2^32
return true;
else
return false;
}