JavaScript USES Object.prototype.toString to determine if it is an array

  • 2020-05-19 04:15:34
  • OfStack

Why use Object.prototype.toString instead of Function.prototype.toString or something? This is related to their toString interpretation. 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 simple to say: 1, get the object's class name (object type). 2. Then combine [object, obtained class name,] and return.
Array is explained in ECMA as follows:

The [[Class]] property of the newly constructed object is set to " Array " .

Therefore, 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 the property detection method. It is really a smart way and a good solution.
In addition, this solution can also be applied to the determination of Date,Function, and other types of objects.

There are several other ways:

var arr = []; return arr instanceof Array; 

Post if there are other good ways.


Related articles: