As far as I know there are three ways of finding out if an object is an Array
by isArray
function if implemented
Array.isArray()
by toString
Object.prototype.toString.apply( obj ) === "[object Array]"
and by instanceof
obj instanceof Array
Is there any reason to choose one over the other?
The best way is probably to use the standard Array.isArray()
, if it's implemented by the engine:
isArray = Array.isArray(myObject)
MDN recommends to use the toString()
method when Array.isArray
isn't implemented:
Compatibility
Running the following code before any other code will create Array.isArray if it's not natively available. This relies on Object.prototype.toString being unchanged and call resolving to the native Function.prototype.call method.
if(!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == '[object Array]'; }; }
Both jQuery and underscore.js[source] take the toString() === "[object Array]"
way.
Unless it was proven that the former has significant performance benefits and my app required every last ounce of speed I would go for the latter.
The reason is readability, pure and simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With