1. typeof
First, we would think of using typeof to detect the data type, but for basic types such as Function, String, Number, Undefined, etc., typeof can detect them all. For example, the code is as follows:
But for arrays or regular expressions, using typeof to detect them will not suffice, because when we detect an array or a regular expression, the returned type will be an object. As shown in the following code:
2. Instanceof
From this, we can easily think of using instanceof to detect whether an object is an instance of an array. This detection returns a boolean. If it is an array, it returns true; otherwise, it returns false. Let's look at the code above to detect whether it is an array:
As can be seen above, using instanceof can indeed determine whether it is an array.
3. constructor property
In JavaScript, every object has a constructor property, which references the constructor function that initialized the object. For example, to determine the type of an unknown object, we can write a method as follows:
As can be seen above, by calling the isArray method, we can also determine whether it is an array.
We can now see that for points 2 and 3, using the instanceof method and the constructor property respectively seem to be able to determine whether it is an array. However, there are exceptions. For example, when using an array from a page across frames (iframe), it will fail, because in different frames (iframes), arrays created do not share their prototype property with each other. The following code test can verify this~
None of the above methods can determine whether an object is an array; however, when we look at ECMA262, we can see that the Object.prototype.toString.call() method can be used to determine whether an object is an array. The code is as follows: