Home Web Front-end JS Tutorial Summary of Several Methods for Determining Object Types in JavaScript_Basic Knowledge

Summary of Several Methods for Determining Object Types in JavaScript_Basic Knowledge

May 16, 2016 pm 05:16 PM
javascript object

We know that the operators for detecting object types in JavaScript are: typeof, instanceof, and the constructor attribute of the object:

1) typeof operator typeof is a unary operator, and the return result is a string describing the type of the operand. For example: "number", "string", "boolean", "object", "function", "undefined" (can be used to determine whether a variable exists). However, typeof has limited capabilities. It returns "object" for Date and RegExp types. Such as:

typeof {}; // "object"
typeof []; // "object"
typeof new Date(); // "object"

So it is only useful when distinguishing between objects and primitive types. To distinguish one object type from another, other methods must be used. Such as: instanceof operator or constructor property of object.

2) instanceof operator. The instanceof operator requires that the operand on the left is an object and the operand on the right is the name or constructor of the object class. The instanceof operator returns true if object is an instance of a class or constructor. Returns false if object is not an instance of the specified class or function, or if object is null. Such as:

[] instanceof Array; // true
[] instanceof Object; // true
[] instanceof RegExp; // false
new Date instanceof Date; // true

So, you can use the instanceof operator to determine whether the object is an array type:

function isArray(arr){
return arr instanceof Array;
}

3) constructor attribute. In JavaScript, each object has a constructor attribute, which refers to the constructor that initializes the object. It is often used to determine the type of unknown objects. For example, given a desired value, use the typeof operator to determine whether it is a primitive value or an object. If it is an object, you can use the constructor attribute to determine its type. So the function to judge the array can also be written like this:

function isArray(arr){
return typeof arr == "object" && arr.constructor == Array;
}

In many cases, we can use the instanceof operator or the constructor property of the object to detect whether the object is an array. For example, many JavaScript frameworks use these two methods to determine whether an object is an array type. But when detecting arrays in cross-frame pages, it fails. The reason is that arrays created in different frames (iframes) do not share their prototype properties with each other. For example:

Copy code The code is as follows:

<script><br>window.onload =function(){<br>var iframe_arr=new window.frames[0].Array;<br>alert(iframe_arr instanceof Array); // false<br>alert(iframe_arr.constructor == Array); // false <br>}<br></script>

I saw an accurate detection method on Ajaxian, calling the toString() method across the prototype chain: Object.prototype.toString(). Can solve the above cross-framework problem. When Object.prototype.toString(o) is executed, the following steps will be performed: 1) Obtain the class attribute of object o. 2) Connection string: "[object " result(1) "]" 3) Return result(2) For example:

Object.prototype.toString.call([]); // Returns "[object Array]"
Object.prototype.toString.call(/reg/ig); // Returns "[object RegExp]"

In this way, we can write a robust function to determine whether the object is an array:

Copy the code The code is as follows:

function isArray(arr){
return Object.prototype.toString.call(arr) === "[object Array]";
}

This method has been recognized by many foreign JavaScript masters and will be used to detect arrays in the upcoming jQuery 1.3. A maintainer of prototype.js wrote the following function, which is used to obtain the type name of an object
Copy code The code is as follows:

/**
 * Returns internal [[Class]] property of an object
 *
 * Ecma-262, 15.2.4.2
 * 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).
 *
 * __getClass(5); // => "Number"
 * __getClass({}); // => "Object"
 * __getClass(/foo/); // => "RegExp"
 * __getClass(''); // => "String"
 * __getClass(true); // => "Boolean"
 * __getClass([]); // => "Array"
 * __getClass(undefined); // => "Window"
 * __getClass(Element); // => "Constructor"
 *
 */
function __getClass(object){
    return Object.prototype.toString.call(object).match(/^[objects(.*)]$/)[1];
};
扩展一下,用于检测各种对象类型:

var is ={
    types : ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
};
for(var i = 0, c; c = is.types[i ]; ){
    is[c] = (function(type){
        return function(obj){
           return Object.prototype.toString.call(obj) == "[object " type "]";
        }
    )(c);
}
alert(is.Array([])); // true
alert(is.Date(new Date)); // true
alert(is.RegExp(/reg/ig)); // true

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

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.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

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

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

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.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

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.

See all articles