How to check whether an object is an array or not in JavaScript?

JavaScript is a loosely typed scripting languages. It has objects which contains name value pairs. While in JavaScript, Array is also an Object, we can use instanceof to check the type of an object. But if there are many frames in a page, if the object is created from a frame which is not at the same global scope as window object, instanceof will not work since Array is a property of window. So how can we determine whether an object is an array or not in JavaScript?

2 ANSWERS



1

In Douglas Crockford's book "JavaScript:The Good Parts". He proposed one method to check whether an object is array or not.

var is_array = function (value) {

return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));

};

First, we ask if the value is truthy. We do this to reject null and other falsy values.Second, we ask if the typeof value is 'object'. This will be true for objects, arrays,and (weirdly) null. Third, we ask if the value has a length property that is a number.This will always be true for arrays, but usually not for objects. Fourth, we ask if thevalue contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?)That will be false for all arrays.

  REPLY  Posted by at 2013-04-08 06:00:25


1

We can use Object.prototype.toString.call(obj)=='[object Array]' to check whether an object is an array. It works even there are many frames in one webpage.

For example:

var arr=[];
alert(Object.prototype.toString.call(arr)=='[object Array]'); //Returns true

var arr=null;
alert(Object.prototype.toString.call(arr)=='[object Array]'); //Returns false

In ECMAScript 5, we can find the Array.isArray() method. It wil work as expected.

if(Array.isArray(arr)){

//arr is an array

}

  REPLY  Posted by at 2013-01-24 06:17:11

Reply to sonic0002 :

This one is cool

  REPLY @

POST ANSWER


Sorry! You need to login first to post answer.

OR

Login with Facebook Login with Twitter


Back to top