Advertisement
Advertisement


How to check if an object is an array?


Question

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.

So how do I check if the variable is an array?


I've rounded up the various solutions below and created a jsperf test. They're all fast, so just use Array.isArray -- it's well-supported now and works across frames.

2020/08/13
1
2833
8/13/2020 9:33:14 PM

Accepted Answer

In modern browsers you can do

Array.isArray(obj)

(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

For backward compatibility you can add the following

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)

If you don't need to detect arrays created in different frames you can also just use instanceof

obj instanceof Array
2014/11/20
1095
11/20/2014 9:16:00 PM


I would first check if your implementation supports isArray:

if (Array.isArray)
    return Array.isArray(v);

You could also try using the instanceof operator

v instanceof Array
2011/01/23

jQuery also offers an $.isArray() method:

var a = ["A", "AA", "AAA"];

if($.isArray(a)) {
  alert("a is an array!");
} else {
  alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2016/08/17

This is the fastest among all methods (all browsers supported):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
2017/02/19

Imagine you have this array below:

var arr = [1,2,3,4,5];

Javascript (new and older browsers):

function isArray(arr) {
  return arr.constructor.toString().indexOf("Array") > -1;
}

or

function isArray(arr) {
  return arr instanceof Array;
}

or

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

then call it like this:

isArray(arr);

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

jQuery:

$.isArray(arr);

Angular:

angular.isArray(arr);

Underscore and Lodash:

_.isArray(arr);
2019/08/21

Array.isArray works fast, but it isn't supported by all versions of browsers. So you could make an exception for others and use universal method:

    Utils = {};    
    Utils.isArray = ('isArray' in Array) ? 
        Array.isArray : 
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }
2013/02/18

Source: https://stackoverflow.com/questions/4775722
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]