x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

How do I know if a variable is an array?

Creating a sample array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];

Method 1:

Array.isArray(fruits);     // returns true

NB: THis method not supported in older browsers.

Method 2:

To overcome the method 1, Cretae an isArray() function
function isArray(x)
{
    return x.constructor.toString().indexOf("Array") > -1;
}

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Method 3:

The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array     // returns true

No comments:

Post a Comment