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?
TOTAL 2 ANSWERS
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 && }; 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. | |
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=[]; var arr=null; In ECMAScript 5, we can find the Array.isArray() method. It wil work as expected. if(Array.isArray(arr)){ //arr is an array } | |
POST ANSWER
Sorry! You need to login first to post answer.
OR
RECENT
- ► Should we be worried about the win of AlphaGo?
- ► Why doesn't IBM file legal brief in support of Apple?
- ► What are the big Internet events in 2015?
- ► Will Elon Musk get into drone business?
- ► What does your work cubicle look like?
- ► What are you most afraid of as a programmer?
- ► Is Apple dead in innovation?
- ► What are bad parts of Windows 10?
- ► What different things have you experienced in Windows 10?
- ► What do you like or dislike about AngularJS?