From those two posts:
There are several ways to check if one object is an array
variable instanceof Array
Array.isArray(variable)
I was told that the second method is better than the first one. Is anyone can tell the reason of it?
No. There are some cases where obj instanceof Array
can be false, even if obj
is an Array
.
You do have to be careful with instanceof in some edge cases, though, particularly if you're writing a library and so have less control / knowledge of the environment in which it will be running. The issue is that if you're working in a multiple-window environment (frames, iframes), you might receive a Date d (for instance) from another window, in which case d instanceof Date will be false — because d's prototype is the Date.prototype in the other window, not the Date.prototype in the window where your code is running. And in most cases you don't care, you just want to know whether it has all the Date stuff on it so you can use it.
Source: Nifty Snippets
This example, applies to array objects too and so on.
And the standard method suggest by ECMAScript standards to find the class of an Object
is to use the toString
method from Object.prototype
and isArray(variable)
uses it internally.
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