JavaScript detection Array

Source: Internet
Author: User

The array in ECMASCRIPT5 has introduced the IsArray method, which is designed to detect whether a variable is an array.

But for IE6, 7 and other ancient browsers, there is no such method, in Zakas wrote a book to pick a function, basically can gracefully meet the majority of needs:

The functions are as follows:

1 functionIsArray (arr) {2   if(typeofArray.isarray = = = "function") {3       returnArray.isarray (arr);4}Else {5         returnObject.prototype.toString.call (arr) = = = "[Object Array]";6     }7 } 8 /*9 code interpretation in the *elseTen *call Changes the ToString's this reference to the object to be detected, returns the string representation of this object, and One * After comparing this string * whether it is ' [object Array] ' to determine if it is an instance of Array. It A * Cannot call the *tostring method of array directly, because it may be modified, and the object - * is the "most primitive" object, very few people dare to touch it and its properties, * so to a certain extent to ensure - * its "purity".  the */

Of course there is a less reliable way, but generally it will work:

1 function IsArray (arr) {2   return typeof Arr.sort () = = = "function";   3 }4/*5* But if an object also contains the sort method, then this function sanitization to sleep ~ ~ with this 6 * method is, you must ensure that all the JS objects in your code do not contain the sort method, so as to 7 * Ensure that this method performs normally.  8* /

JavaScript detection Array

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.