Use Object. prototype. toString in JavaScript to determine whether it is an array _ javascript skill

Source: Internet
Author: User
This article mainly introduces how to use Object in JavaScript. prototype. toString determines whether it is an array. This article describes the Object. prototype. toString related knowledge, and provides the implementation code to judge the array. using this method, you can also determine other data types of javascrpty. if you need it, you can refer to why Object is used. prototype. toString instead of Function. prototype. toString or other? 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.