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