Use Object.prototype.toString in JavaScript to determine whether an array

Source: Internet
Author: User

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.

Related Article

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.