Question

Say I have a function like so:

function foo(bar) {
    if (bar > 1) {
       return [1,2,3];
    } else {
       return 1;
    }
}

And say I call foo(1), how do I know it returns an array or not?

Was it helpful?

Solution

I use this function:

function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

Is the way that jQuery.isArray is implemented.

Check this article:

OTHER TIPS

if(foo(1) instanceof Array)
    // You have an Array
else
    // You don't

Update: I have to respond to the comments made below, because people are still claiming that this won't work without trying it for themselves...

For some other objects this technique does not work (e.g. "" instanceof String == false), but this works for Array. I tested it in IE6, IE8, FF, Chrome and Safari. Try it and see for yourself before commenting below.

Here is one very reliable way, take from Javascript: the good parts, published by O'Reilly:

if (my_value && typeof my_value === 'object' &&  typeof my_value.length === 'number' &&
!(my_value.propertyIsEnumerable('length')) { // my_value is truly an array! }

I would suggest wrapping it in your own function:

function isarray(my_value) {

    if (my_value && typeof my_value === 'object' &&  typeof my_value.length === 'number' &&
        !(my_value.propertyIsEnumerable('length')) 
         { return true; }
    else { return false; }
}

As of ES5 there is isArray.

Array.isArray([])  // true

To make your solution more general, you may not care whether it is actually an Array object. For example, document.getElementsByName() returns an object that "acts like" an array. "Array compliance" can be assumed if the object has a "length" property.

function is_array_compliant(obj){
    return obj && typeof obj.length != 'undefined';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top