3

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?

8
  • 1
    It depends. How do you define "array"? tags isn't an Array.
    – SLaks
    Mar 6, 2014 at 22:36
  • If they both return false, chances are they got it right, and you're wrong, and it's not really an array.
    – adeneo
    Mar 6, 2014 at 22:40
  • 1
    @adeneo: Specifically, it's a NodeList.
    – SLaks
    Mar 6, 2014 at 22:49
  • @SLaks - Indeed, and it's even "live" !
    – adeneo
    Mar 6, 2014 at 22:51
  • but the usage of the returned value is exactly like an array, and you traverse it just like an array. Why would you want it to return a false value?
    – Chihung Yu
    Mar 6, 2014 at 22:51

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.