Home  >  Article  >  Web Front-end  >  Using Object.prototype.toString in JavaScript to determine whether it is an array_javascript tips

Using Object.prototype.toString in JavaScript to determine whether it is an array_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:06:321213browse

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:

Copy code 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. Then combine [object, obtained class name,] and return.
ECMA has the following description of Array:
Copy code 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:
Copy code 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 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:
Copy code The code is as follows:

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