Why use Object.prototype.toString instead of Function.prototype.toString or something? This is related to the way their ToString is interpreted. The following is an explanation of the 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: 1, get the object's class name (object type). 2, and then the [object, get the class name,] combined and returned.
The array is described in ECMA as follows:
The code is as follows:
The [[Class]] property of the newly constructed object is set to "Array".
So we use the following code to detect the array:
The code is as follows:
function IsArray (o) {return Object.prototype.toString.call (o) = = ' [Object Array] ';}
This method not only solves the problem of instanceof, but also solves the problems existing in the method of attribute detection, which is a kind of coup and a good solution.
In addition, this solution can also be used to determine the types of objects such as date,function.
There are several other ways:
The code is as follows:
var arr = []; return arr instanceof Array;
If there are other good ways to post it.