The optimal way to determine the type of an array

What is the best way to determine the type of an object: Array and why ?.

var arr = [];

// Method #1
Array.isArray(arr);

// Method #2 
toString.call(arr) == "[object Array]"

// Method #3
arr.constructor == Array

      

+3


source to share


2 answers


All three methods can be used to check if a variable is of type Array. However, there are some nuances. I'll start from the last to the first.

Method # 3. Will not work if the variable in question is derived from another winndow / frame. In this case, the constructor will point to another object Array

, and this check will return false

. For the same reason, arr instanceof Array

it is not bulletproof. So it's not 100% reliable.



Method # 2 . This is the method traditionally used to check the type of an array. In fact, Array.isArray

polyfill is based on this method. The only drawback is that it is cumbersome and verbose.

Method # 1 . Is this one of ES5 that should finally be used to check the type of an array, no matter which realm array is from (like iframe). This is the very best on the list.

+3


source


The preferred method is to use Array.isArray

. This is present in the ES5 language specification and is fairly well supported by browsers.

If you plan on supporting older browsers, you can find the polyfill on MDN . polyfill is basically your second option.

The latter will not work if you are playing with iframes.



var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false

      

The reason is that the constructor is Array

different for every object window

. Using this to detect arrays will work 99% of the time, but it will suddenly crash one day.

0


source







All Articles