Javascript isArray type detection function

Source: Internet
Author: User

1. typeof operator. For Function, String, Number, and Undefined objects, there is no problem, but the objects for Array are useless:
Js Code
Copy codeThe Code is as follows:
Alert (typeof null); // "object"
Alert (typeof []); // "object"

2. instanceof operator. This operator checks whether the prototype object's prototype chain points to the prototype object of the constructor. Well, it sounds good and should solve our array detection problem:
Js Code
Copy codeThe Code is as follows:
Var arr = [];
Alert (arr instanceof Array); // true

3. constructor attribute of the object. In addition to instanceof, we can also use each object to have the constructor attribute to determine its type, so we can do this:
Js Code
Copy codeThe Code is as follows:
Var arr = [];
Alert (arr. constructor = Array); // true

It seems that the last two solutions are impeccable, but is that true? The sky is unpredictable. When you move back and forth between multiple frames, the following frustrating problem occurs:
Js Code
Copy codeThe Code is as follows:
Var iframe = document. createElement ('iframe ');
Document. body. appendChild (iframe );
XArray = window. frames [window. frames. length-1]. Array;
Var arr = new xArray (1, 2, 3); // [1, 2, 3]
// Alas!
Arr instanceof Array; // false
// Alas!
Arr. constructor === Array; // false

Since each iframe has its own execution environment, objects instantiated across frames do not share the prototype chain with each other, so the above detection code becomes invalid! What should I do ?? Well, javascript is a dynamic language. Maybe the "duck-type" (duck type) of hichina oil can help us. "If it starts to look like a duck, it also sounds like a duck, then let's look at it as a duck. "Similarly, we can detect the unique capabilities of some array objects for judgment. This method has already been used, such as the Prototype framework, to see what it implements. isArray method:
Js Code
Copy codeThe Code is as follows:
IsArray: function (object ){
Return object! = Null & typeof object = "object "&&
'Splice 'in object & 'join' in object;
}

IsArray: "object. Do you have the methods exclusive to the splice and join arrays ?"
Object: "Well, yes, I have !"
IsArray: "Well, you are an array, even if you pretend to be, then ......"
Js Code
Copy codeThe Code is as follows:
Var trickster = {splice: 1, join: 2 };
Object. isArray (trickster); // counterfeit success, yeah

Yes, this solution is a bit awkward. Any object with the 'splice 'and 'join' attributes can pass this check! What should I do ?? Don't worry. Think about it. In fact, what we need is a method that can acquire the actual object type and be used across frames. This is not the case. Careful foreigners found this when reading the ECMA262 standard (btw, I also saw it. Why didn't I find this purpose? Thanks ):
The ECMA-262 wrote
Copy codeThe 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 above Specification defines Object. prototype. toString behavior: first, obtain an internal attribute of the object [[Class], and then, based on this attribute, returns a string similar to "[object Array]" as the result (we should all know after reading the ECMA standard, [[] is used to indicate the attributes used inside the language and which cannot be accessed externally, is called "Internal attribute "). With this method, combined with call, we can obtain the internal attribute [[Class] of any object, and then convert the type detection to string comparison to achieve our goal. Let's take a look at the description of the Array in the ECMA standard:
The ECMA-262 wrote
Copy codeThe Code is as follows:
New Array ([item0 [, item1 [,…])
The [[Class] property of the newly constructed object is set to "Array ".

Therefore, you can rewrite the previous isArray function to use this feature as follows:
Js Code
Copy codeThe Code is as follows:
Function isArray (o ){
Return Object. prototype. toString. call (o) = '[object Array]';
}

Call changes the this reference of toString to the object to be checked, returns the string representation of the object, and then compares whether the string is '[ object Array] 'to determine whether it is an Array instance. Maybe you have to ask, why isn't o. toString () directly ()? Well, although Array inherits from Object, there will also be the toString method, but this method may be rewritten and cannot meet our requirements, and Object. prototype is the tiger's ass, and few people dare to touch it, so it can be "pure" to a certain extent ":)
Different from the previous solutions, this method solves the problem of cross-frame object construction. After testing, the compatibility of various browsers is also good and can be safely used. The good news is that many frameworks, such as jQuery and Base2, plan to use this method to implement some special types of objects, such as arrays and regular expressions, you don't have to write it yourself.

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.