Home Web Front-end JS Tutorial Summary of how JavaScript uses operators and properties to determine object type

Summary of how JavaScript uses operators and properties to determine object type

Jul 26, 2017 am 11:52 AM
javascript js operator

The operators used to detect object types in JavaScript include: typeof, instanceof, and the constructor attribute of the object:

1) typeof operator typeof is a unary operator, 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"
Copy after login

So it is only useful when distinguishing objects and primitive types. To distinguish one object type from another, other methods must be used. Such as: instanceof operator or constructor attribute 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. For example:


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

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


function isArray(arr){ 
  return arr instanceof Array; 
}
Copy after login

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 value to be determined, 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 determine the array can also be written like this:


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

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:


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

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([]); // Return " [object Array]"
Object.prototype.toString.call(/reg/ig); // Return "[object RegExp]"

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


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

This method has been recognized by many foreign javaScript masters. This method 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


/**
 * 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(&#39;&#39;); // => "String"
 * __getClass(true); // => "Boolean"
 * __getClass([]); // => "Array"
 * __getClass(undefined); // => "Window"
 * __getClass(Element); // => "Constructor"
 *
 */
function __getClass(object){
  return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
};
Copy after login

Extend it to detect various object types:


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
Copy after login

The above is the detailed content of Summary of how JavaScript uses operators and properties to determine object type. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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

Analysis of the meaning and usage of += operator in C language Analysis of the meaning and usage of += operator in C language Apr 03, 2024 pm 02:27 PM

The += operator is used to add the value of the left operand to the value of the right operand and assign the result to the left operand. It is suitable for numeric types and the left operand must be writable.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

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.

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

Operator precedence list in Go language, which operator has the highest precedence? Operator precedence list in Go language, which operator has the highest precedence? Jan 03, 2024 pm 04:59 PM

There are many operators in Go language, which are often used to perform various mathematical and logical operations. Each operator has its own precedence, which determines the order in which they are evaluated in an expression. This article will introduce you to the priority ranking of operators in the Go language and find out the operator with the highest priority. The operators in Go language are as follows in order from high to low precedence: parentheses: (). Parentheses are used to change the precedence order of operators. Parentheses in expressions are evaluated first. Unary operators: +, -, !. Unary operator means that only one

See all articles