Short answer:
if (obj instanceof Array) {
// obj is an array
}
Or, if you don't know whether obj
is defined or not:
if ((typeof obj !== "undefined") && (obj instanceof Array)) {
// obj is an array
}
To discuss why yours aren't quite right:
obj.anyProperty
will throw a ReferenceError
if obj
is undefined. This affects all four of the things you put.
if (obj.length)
will evaluate to false for an empty array, which isn't what you want. Because the length is 0 (a falsy value), it will falsely be inaccurate. This could also have issues if another object has a length
property.
if (obj.length === undefined)
will usually work, but it's frowned upon because undefined
can be redefined. Someone could break your code by writing undefined = obj.length
. This can also create false negatives; obj
could happen to have a property called "length" and it would falsely call it an array.
if (typeof obj.length === "undefined")
works fine, but could detect the same false negatives as the above.
if (obj.length == null)
will work okay, but has the same bugs as above. In a double-equals (==
), it matches null
and undefined
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…