Thursday, 10 November 2016

javascript - Difference between using Array.isArray and instanceof Array



There is two ways to figure out if an array is an array or an object. Using typeof item === "object"; will return true for an object and an array since arrays are relatively new to javascript and arrays are prototypes of objects(may have worded this wrong, feel free to correct me). So the two ways I know of to determine if an Array is an Array are:



Solution 1:



Array.isArray(item);



Solution 2:



item instanceof Array;


My questions are:




  1. What is the difference between these two solutions?

  2. Which of these two is the preferred solution?


  3. Which has a faster process time?


Answer




1.What is the difference between these two solutions?




isArray is an ES5 method so not supported by older browsers, but it reliably determines if an object is an Array.



instanceof only checks if Array.prototype is on an object's [[Prototype]] chain. It fails when checking arrays across frames since the Array constructor used for the instance will likely be different to the one used for the test.





2.Which of these two is the preferred solution?




"Preferred" assumes some criterion for selection. Generally, the preferred method is something like:



if (Object.prototype.toString.call(obj) == '[object Array]')



which suits ES3 browsers and works across frames. If only ES5 browsers are in consideration, isArray is likely OK.




3.Which has a faster process time?




Largely irrelevant, since the processing time for both is negligible. Far more important to select the one that is reliable. An Array.isArray method can be added to browsers that don't have it built–in using:



if (!Array.isArray) {
Array.isArray = function(obj) {

return Object.prototype.toString.call(obj) == '[object Array]';
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...