Javascript isArray array type detection function_javascript skills
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
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
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
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
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
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
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
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
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
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
