Home > Web Front-end > JS Tutorial > body text

Javascript isArray array type detection function_javascript skills

WBOY
Release: 2016-05-16 18:45:01
Original
1290 people have browsed it

1. typeof operator. There will be no problem for objects of types Function, String, Number, and Undefined, but there is no use for Array objects:
Js code

Copy code The code is as follows:

alert(typeof null); // "object"
alert(typeof []); // " object"

2. instanceof operator. This operator detects whether the prototype chain of the object points to the prototype object of the constructor. Well, it sounds good and should be able to solve our array detection problem:
Js code
Copy code The code is as follows:

var arr = [];
alert(arr instanceof Array); // true

3. The constructor property of the object. In addition to instanceof, we can also use the constructor property of each object to determine its type, so we can do this:
Js code
Copy code The code is as follows:

var arr = [];
alert(arr.constructor == Array); // true

It seems that the last two solutions are impeccable, but are they really so? Unforeseen circumstances arise, and when you shuttle back and forth between multiple frames, frustrating problems arise:
Js code
Copy code The 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]
// Oops!
arr instanceof Array; // false
// Oops!
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 This causes the above detection code to fail! What should I do? ? Well, JavaScript is a dynamic language. Maybe the snake oil "duck type" can help us. "If it walks like a duck and quacks like a duck, then treat it as a duck." Same reason , which can detect the unique capabilities of certain array objects to make judgments. This method has been used by some people, such as the Prototype framework. Let’s take a look at the Object.isArray method it implements:
Js code
Copy code The 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 two array-specific methods of splice and join? "
object: "Well, yes, I have it! "
isArray: "Okay, then you are an array, even if you are pretending, 囧..."
Js code
Copy code The code is as follows:

var trickster = { splice: 1, join: 2 };
Object.isArray(trickster); // Fake successfully, yeah

Yes, this solution feels a bit awkward, any object with 'splice' and 'join' properties can Pass this test! What to do, what to do, what to do? ? Don't worry, think about it carefully. In fact, what we need is a method that can get the actual type of the object and can be used across frames. No, a careful foreigner discovered this when reading the ECMA262 standard (btw, I also read it, why didn’t I find this use, 囧):
ECMA-262 wrote
Copy code 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 above specification defines the behavior of Object.prototype.toString: first, obtain an internal property [[Class]] of the object, and then return a string similar to "[object Array]" as the result based on this property (Those who have read the ECMA standard should know that [[]] is used to represent attributes used internally in the language and not directly accessible from the outside, called "internal attributes"). Using this method, combined with call, we can obtain the internal attributes [[Class]] of any object, and then convert the type detection into string comparison to achieve our purpose. Let’s first take a look at the description of Array in the ECMA standard:
ECMA-262 wrote
Copy the code The code is as follows :

new Array([ item0[, item1 [,…]]])
The [[Class]] property of the newly constructed object is set to “Array”.

So, you can rewrite the previous isArray function to take advantage of this feature, as follows:
Js code
Copy code The 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 detected, returns the string representation of this object, and then compares whether this string is '[object Array]' to determine whether it is an instance of Array . Maybe you want to ask, why not o.toString() directly? Well, although Array inherits from Object, it will also have a toString method, but this method may be rewritten and fail to meet our requirements, and Object.prototype is the butt of a tiger, and few people dare to touch it, so It can guarantee its "purity" to a certain extent:)
Different from the previous solutions, this method solves the problem of cross-frame object construction very well. After testing, the compatibility of major browsers is also very good, so you can rest assured use. The good news is that many frameworks, such as jQuery, Base2, etc., plan to use this method to implement certain types of special objects, such as arrays, regular expressions, etc., without having to write them ourselves.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!