jQuery and Array isArray are not working correctly
If I do:
var tags = document.getElementsByTagName('div');
jQuery.isArray(tags) // returns false
Array.isArray(tags) // returns false
function isArray(object){
return typeof object === "object" && object.length > -1;
}
isArray(tags) // return true
This issue causes an actual bug on my website:
On my website I have a form tag with inputs name "plan".
If I only have one input name "plan", it will return an none array.
But if I have two inputs and both have name "plan", it will return an array.
I used jQuery.isArray to check if it's an array or not but was forced to abandon using jQuery isArray.
People commented that it's nodelist but the usage of nodelist is exactly like an array. So under what circumstances you would actually want to avoid it to use like an array?
No, it's working correctly. getElementsByTagName returns a nodelist - an array-LIKE object but not an actual array, so jQuery is right to return false.
Your function is returning true because it is testing for the type being an object (a nodelist is an object) and it having a length (a nodelist has a length).
If you truly want to test for an array use foo instanceof Array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With