Monkey Raptor

Saturday, May 9, 2015

JavaScript: Check Whether an Object Is an Array

#1 Using instanceof operator #
Example:
Additional

Checking object #
This operator can also check if the input is an object, by using Object built-in constructor. As such:

Or, we can use typeof method.
For example:
typeof will return "object" (string) keyword for either object or array type input. Therefore, this operator can't be used for checking "array" input.

Checking function #
We can check whether an object is a function:

Or, using typeof operator.
For example:

Checking string and number #
We can use typeof for those.
As such:

Checking element #
We can use instanceof for that.
Example:

#2 Using Array.isArray(the_array) method #

In conclusion #
There are 2 ways we can choose to check the "array"-ness.
  1. the_array instanceof Array
  2. Array.isArray(the_array) (supported on IE9+ and other current browsers)
For instanceof operator, we can create a custom constructor for a particular object we wanna test. More documentation at MDN
JavaScript: Check Whether an Object Is an Array
https://monkeyraptor.johanpaul.net/2015/05/javascript-check-whether-object-is-array.html

No comments

Post a Comment

Tell me what you think...