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
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
Breakpoint |
By sonic0002 |
RECENT
- ► What Chrome extensions do you find useful for programmers?
- ► What does your personal desk look like?
- ► Happy Chinese New Year for those who celebrate it
- ► How much time do you code every day?
- ► What lies would programmers like to tell?
- ► Is GoLang being used in more and more startups?
- ► How do you feel about 996?
- ► What are your reasons not writing blogs?
- ► Why do you or do not write tech blogs?
- ► What weekend projects have you created?