Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript way to tell if an object is an Array [duplicate]

Tags:

javascript

What's the 'right' way to tell if an object is an Array?

function isArray(o) { ??? }

like image 702
Damien Avatar asked May 28 '10 21:05

Damien


2 Answers

The best way:

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

The ECMAScript 5th Edition Specification defines a method for that, and some browsers, like Firefox 3.7alpha, Chrome 5 Beta, and latest WebKit Nightly builds already provide a native implementation, so you might want to implement it if not available:

if (typeof Array.isArray != 'function') {
  Array.isArray = function (obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  };
}
like image 192
Christian C. Salvadó Avatar answered Sep 27 '22 19:09

Christian C. Salvadó


You should be able to use the instanceof operator:

var testArray = [];

if (testArray instanceof Array)
    ...
like image 26
Chad Birch Avatar answered Sep 27 '22 20:09

Chad Birch