Why use Object.prototype.toString instead of Function.prototype.toString or others? This is related to their toString interpretation method. The following is the explanation of Object.prototype.toString in ECMA:
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. Then combine [object, obtained class name,] and return.
ECMA has the following description of Array:
The [[Class]] property of the newly constructed object is set to “Array”.
So we use the following code to detect the array:
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 method. It is really a coup and a good solution.
In addition, this solution can also be applied to determine objects of Date, Function and other types.
There are several other methods:
var arr = []; return arr instanceof Array;
If there are other good methods, please post them.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn