Is this an acceptable way to determine if an object is an array in JavaScript?

I often used this code to determine if an array is really an array ...

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

I recently started changing my callback tests from typeof callback == 'function' to callback instanceof Function , because I read that Safari and Chrome will tell you that the regex literal is a function using the first (and that was when I tested it).

Now I decided to check this code to see if I can replace the detailed code above ...

 array instanceof Array 

It worked.

Comparing both on jsFiddle .

So, are there any problems with the latter method? I suggested that this could be because the first code sample appeared on Google much more often.

+4
source share
6 answers

Two problems using instanceof for an array:

  • Returns false when the array is from another window or frame.
  • Aborted if the Array constructor was overwritten

The following is a kangax article where I first saw your first technique (also used in jQuery): http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

+2
source

In ES5, you can call:

 Array.isArray(obj); 

See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray

See also their note , where they say that a pure Javascript implementation cannot be guaranteed 100% emulation of a version of native code.

+3
source

If this helps, here is how to do it in jQuery.isArray :

 isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; } type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; } 

ToString:

 toString = Object.prototype.toString 

class2type is an associative array that is initialized as:

 jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); 

If this is any indication, jQuery uses your first method and thoroughly tests it.

+2
source

There is a problem if someone overwrites your global Array variable. Pretty unlikely, but if you want a truly fail-safe method, stick with # 1.

Demonstration on jsFiddle .

0
source

no problem with the method

 array instanceof Array 

you can use function

 function is_array( mixed_var ) { // Finds whether a variable is an array return ( mixed_var instanceof Array ); } 
0
source

An alternative is the Ext method:

 function isArray (obj) { return obj != null && typeof obj == 'object' && 'splice' in obj && 'join' in obj; } 

It depends on checking the existence of splice and join. Two functions that should only be in an array. Of course, this will fail if you pass in an object that had functions called splice and join (and was not an array), but then you probably shouldn't do this in the first place.

0
source

Source: https://habr.com/ru/post/1344055/


All Articles