Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if an object is an array or not in Javascript?

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?

like image 500
Artilheiro Avatar asked Jul 29 '09 20:07

Artilheiro


1 Answers

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:

  • isArray: Why is it so bloody hard to get right?
like image 185
Christian C. Salvadó Avatar answered Oct 11 '22 12:10

Christian C. Salvadó