In JavaScript, Object. prototype. toString is used to determine whether it is an array.
Why Object. prototype. toString instead of Function. prototype. toString or others? This is related to their toString interpretation method. The following is an explanation of Object. prototype. toString in ECMA:
The Code is as follows:
Object. prototype. toString ()
When the toString method is called, the following steps are taken:
1. Get the [[Class] property of this object.
2. Compute a string value by concatenating the three strings "[object", Result (1), and "]".
3. Return Result (2)
The process is simply as follows: 1. Get the class name (Object Type) of the object ). 2. Combine [object, obtained class name,] and return it.
The Array in ECMA is described as follows:
The Code is as follows:
The [[Class] property of the newly constructed object is set to "Array ".
Therefore, we use the following code to detect Arrays:
The Code is as follows:
Function isArray (o) {return Object. prototype. toString. call (o) ===' [object Array] ';}
This method not only solves the cross-page problem of instanceof, but also solves the problem of attribute detection. It is a great solution.
In addition, this solution can also be used to determine the types of objects such as Date and Function.
There are also several methods:
The Code is as follows:
Var arr = []; return arr instanceof Array;
If you have other good methods, paste them.