Javascript IsArray Array type detection function _javascript tips

Source: Internet
Author: User
1, typeof operator. There are no problems with functions, String, number, undefined objects of these types, but objects for array are useless:
JS Code
Copy Code code as follows:

Alert (typeof null); "Object"
Alert (typeof []); "Object"

2, instanceof operator. This operator detects whether the object's prototype chain points to the prototype object of the constructor, well, sounds good, and should be able to solve our array detection problem:
JS Code
Copy Code code as follows:

var arr = [];
Alert (arr instanceof Array); True

3, the object's constructor property. In addition to instanceof, we can use each object to have constructor attributes to determine its type, so we can do this:
JS Code
Copy Code code as follows:

var arr = [];
Alert (Arr.constructor = = Array); True

It looks like the latter two solutions are unassailable, but is it really? When you are moving back and forth through multiple frame, the frustrating problem arises:
JS Code
Copy Code code 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]
Oh!
Arr instanceof Array; False
Oh, my God!
Arr.constructor = = Array; False

Because each IFRAME has its own execution environment, objects that are instantiated across the frame do not share the prototype chain with each other, causing the above detection code to fail! How to do?? Well, JavaScript is a dynamic language, perhaps the "Duck type" (duck type) can help us "if it walks like a duck and barks like a duck, then he is a duck", and, similarly, can detect the ability of certain array objects to make judgments, This method has already been used, such as the prototype frame, to see how it implements the Object.isarray:
JS Code
Copy Code code as follows:

Isarray:function (object) {
Return object!= null && typeof Object = = "Object" &&
' Splice ' in Object && ' join ' in object;
}

IsArray: "Object, do you have splice, join these two arrays peculiar to the method?" ”
Object: "Well, yes, I have!" ”
IsArray: "Well, then you are the number group, even if you are impersonating, embarrassing ..."
JS Code
Copy Code code as follows:

var trickster = {splice:1, join:2};
Object.isarray (trickster); Fake success, yes

Yes, this solution feels a bit awkward, and any object with the ' splice ' and ' join ' attributes can be detected! How to do how to do?? Don't worry, think about it, what we need is a way to get the actual type of the object and to use it across frame. This does not, the careful foreigner browses the ECMA262 standard time to discover this (btw, I also looked, how did not discover this use, embarrassed):
ECMA-262 wrote
Copy Code code as follows:

Object.prototype.toString () when the "toString" 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 the behavior of the Object.prototype.toString: first, get an internal property of an object [[Class]], and then, based on this property, returns a similar to "[Object Array]" string as a result (read the ECMA standard should know that [[]] is used to represent an externally inaccessible property, called an "internal property," used within a language.) Using this method, and then with call, we can get the internal properties [[Class]] of any object, and then convert the type detection into string comparisons to achieve our goal. Let's take a look at the description of array in the ECMA standard:
ECMA-262 wrote
Copy Code code as follows:

New Array ([item0[, Item1 [,...]])
The [[Class]] property of the newly constructed object is set to "Array".

Thus, you can rewrite the previous IsArray function to take advantage of this feature, as follows:
JS Code
Copy Code code as follows:

function IsArray (o) {
return Object.prototype.toString.call (o) = = ' [Object Array] ';
}

Call Change ToString This refers to the object to be instrumented, returns a string representation of this object, and then compares whether the string is ' [object Array] ' to determine whether it is an instance of Array. Perhaps you have to ask, why not directly o.tostring ()? Well, although the array inherits from object, there will be the ToString method, but this method may be rewritten to meet our requirements, and Object.prototype is the tiger's butt, few people dare to touch it, so to a certain extent to ensure its "purity":
Unlike the previous scenarios, this method is a good solution to the problem of building a cross frame object, after testing, the major browser compatibility is also very good, you can rest assured that the use. The good news is that many frameworks, such as jquery, Base2, and so on, plan to use this method to implement certain types of objects, such as arrays, regular expressions, and so on, without our own writing.
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.