


Give an example to explain how to determine the type of object in JavaScript_Basic knowledge
In the process of writing js programs, you may often need to determine the type of an object. For example, if you write a function, you need to write different codes by determining different parameter types.
First of all, you may think of the typeof operator. Look at the following example:
<script type="text/javascript"> var object = {}; var b = true; alert(typeof object + " " + typeof b); </script>
The result obtained is as follows:
As you can see from the above results, the typeof operator can be used to display the type of the object. So what are the results of null and undefined in the scope of the typeof operator?
/*var object = {}; var b = true; alert(typeof object + " " + typeof b);*/ alert(typeof null + " " + typeof undefined)
The typeof operator acts on null and actually displays "object" (this seems unscientific, I thought it would display "null'" ), acting on undefined displays "undefined" (this is in line with the result we want), so when using the typeof operator to determine the type of an object, be particularly careful because the object may be null. The above only gives a part of the results of typeof operating on these objects. The following table lists the results of typeof operator operating on Boolean, Number, String, Array, Date, RegExp, Object, Function, null, undefined (interested readers You can test it yourself):
From the results in the above table, we can see that Array, Date, and RegExp all display objects. Why are they not directly displaying the object type? Woolen cloth? This will lead to another operator of js: instanceof operator. This operator is used to determine whether an object is a certain type of object. The calculated value is true or false. Let’s take a look first:
var now = new Date(); var pattern = /^[\s\S]*$/; var names = ['zq', 'john']; alert((now instanceof Date) + " " + (pattern instanceof RegExp) + " " + (names instanceof Array));
Obviously the type of the object can be determined through this instanceof, but this can only determine other than the basic type. For other types (including String type), he cannot determine the basic type. However, instanceof cannot always be judged normally. Consider the situation of a frame. To judge whether the object of its type is an object passed by another frame, first look at the following example.
main.html
<!doctype html> <html lang="en"> <head> <title>Main</title> </head> <frameset cols="45%,*"> <frame name="frame1" src="frame1.html"/> <frame name="frame2" src="frame2.html"/> </frameset> </html>
frame1.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame1</title> </head> <script type="text/javascript"> var names = ['riccio zhang', 'zq', 'john']; </script> <body style="background: #ccc"> </body> </html>
frame2.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame2</title> <script type="text/javascript"> document.write("top.frame1.names instanceof Array:" + (top.frame1.names instanceof Array)); document.write("<br/>"); document.write("top.frame1.names instanceof top.frame1.Array:" + (top.frame1.names instanceof top.frame1.Array)); document.write("<br/>"); document.write("top.frame1.Array === top.frame2.Array?" + (top.frame1.Array === top.frame2.Array)); </script> </head> <body style="background: #747474"> </body> </html>
The names object is in the frame1 frame. At this time, it is created through the Array of the frame1 frame. If the names object is taken to the Array in frame2 for comparison, Obviously names is not an instance of Array in frame2. It is thought that frame1 and frame2 are not the same Array at all. From the second actual result, it can be clearly seen that names is an instance of the frame in which it is located. From the third output, it can be seen that It can be seen that the Array of frame1 and the Array of frame2 are different. So what should we do when encountering the above cross-frame comparison? We can't compare the Array corresponding to the frame every time. There is a necessary way to solve the above problem. Look at the following code:
var toString = {}.toString; var now = new Date(); alert(toString.call(now))
{}.toString means to obtain the toString method on the Object object (this method is one of the basic methods of the Object object), and toString.call(now) means to call the toString method. Calling the most native toString() method of the Date object (this method is the method on Object) can display a string of type [object Date]. If it is an Array, the words [object Array] will be generated, that is to say, perform the above The operation will display words similar to [object Class], so can we know its type just by judging the string? From this, the following tool class can be written:
tools.js
var tools = (function(undefined){ var class2type = {}, toString = {}.toString; var fun = { type: function (obj){ return obj === null || obj === undefined ? String(obj) : class2type[toString.call(obj)] }, isArray: function (obj){ return fun.type(obj) === "array"; }, isFunction: function (obj){ return fun.type(obj) === "function"; }, each: function (arr, callback){ var i = 0, hasLength = arr.length ? true : false; if(!callback || (typeof callback !== 'function') || !hasLength){ return; } for(i = 0; i< arr.length; i++){ if(callback.call(arr[i], i, arr[i]) === false){ break; } } } }; fun.each("Boolean Number String Array Date RegExp Object Function".split(" "), function(i, name){ class2type["[object "+ name +"]"] = name.toLowerCase(); }); return fun; })();
tools provides methods such as type, isArray, isFunction to determine the type of the object. According to the actual If necessary, you can add your own method to determine the type. type accepts an obj parameter, which returns the actual type of the object in lowercase. For example, if you need to determine the type of the object is Array, then this method will return array.
Rewrite it based on the tool class provided above The above example:
fram2.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame2</title> <script type="text/javascript" src="tools.js"></script> <script type="text/javascript"> document.write("top.frame1.names instanceof Array:" + (top.frame1.names instanceof Array)); document.write("<br/>"); document.write("top.frame1.names instanceof top.frame1.Array:" + (top.frame1.names instanceof top.frame1.Array)); document.write("<br/>"); document.write("top.frame1.Array === top.frame2.Array?" + (top.frame1.Array === top.frame2.Array)); document.write("<br/>"); document.write("tools.isArray(top.frame1.names)?" + tools.isArray(top.frame1.names)); </script> </head> <body style="background: #747474"> </body> </html>
At this point, the type of object can be easily determined through the above class. .
Note: Elements such as alert cannot be judged in IE.

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

AI Hentai Generator
Generate AI Hentai for free.

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



Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.
