Let's talk about the difference between typeof and instanceof
Mar 11, 2022 am 11:25 AMtypeof和instanceof操作符都可用來判斷數(shù)據(jù)類型,那么它們之間有什么差異?下面本篇文章就來帶大家了解 typeof 和 instanceof ,聊聊它們的區(qū)別,希望對(duì)大家有所幫助!
typeof
和instanceof
操作符都是用來判斷數(shù)據(jù)類型的,但是它們的使用場(chǎng)景卻各不相同,其中一些細(xì)節(jié)也需要特別注意。接下來讓我們一探究竟,徹底掌握該知識(shí)點(diǎn),再也不懼面試官的提問。
typeof
typeof
是一個(gè)一元運(yùn)算符,放在一個(gè)運(yùn)算數(shù)前面,這個(gè)運(yùn)算數(shù)可以是任何類型。它返回一個(gè)字符串,說明運(yùn)算數(shù)的類型。請(qǐng)看栗子:
const type = typeof '中國(guó)萬歲'; // string typeof 666; // number typeof true; // boolean typeof undefined; // undefined typeof Symbol(); // symbol typeof 1n; // bigint typeof () => {}; // function typeof []; // object typeof {}; // object typeof new String('xxx'); // object typeof null; // object
通過以上例子可以看出,typeof
只能準(zhǔn)確判斷基本數(shù)據(jù)類型和函數(shù)(函數(shù)其實(shí)是對(duì)象,并不屬于另一種數(shù)據(jù)類型,但也能夠使用 typeof 進(jìn)行區(qū)分),無法精確判斷出引用數(shù)據(jù)類型(統(tǒng)統(tǒng)返回 object)。
有一點(diǎn)需要注意,調(diào)用typeof null
返回的是object
,這是因?yàn)樘厥庵?code>null被認(rèn)為是一個(gè)對(duì)空對(duì)象的引用(也叫空對(duì)象指針)。
如果想準(zhǔn)確判斷引用數(shù)據(jù)類型,可以用instanceof
運(yùn)算符。
instanceof
instanceof
運(yùn)算符放在一個(gè)運(yùn)算數(shù)的后面,給定對(duì)象的前面。它返回一個(gè)布爾值,說明運(yùn)算數(shù)是否是給定對(duì)象的實(shí)例:
const result = [] instanceof Array; // true const Person = function() {}; const p = new Person(); p instanceof Person; // true const message = new String('xxx'); message instanceof String; // true
區(qū)別
typeof 會(huì)返回一個(gè)運(yùn)算數(shù)的基本類型,instanceof 返回的是布爾值
instanceof 可以準(zhǔn)確判斷引用數(shù)據(jù)類型,但是不能正確判斷基本數(shù)據(jù)類型
typeof 雖然可以判斷基本數(shù)據(jù)類型(null 除外),但是無法判斷引用數(shù)據(jù)類型(function 除外)
擴(kuò)展
Object.prototype.toString.call()
typeof
和instanceof
都有一定的弊端,并不能滿足所有場(chǎng)景的需求。如果需要通用檢測(cè)數(shù)據(jù)類型,可以使用Object.prototype.toString.call()
方法:
Object.prototype.toString.call({}); // "[object Object]" Object.prototype.toString.call([]); // "[object Array]" Object.prototype.toString.call(666); // "[object Number]" Object.prototype.toString.call('xxx'); // "[object String]"
注意,該方法返回的是一個(gè)格式為"[object Object]"
的字符串。
封裝函數(shù)
為了更方便的使用,我們可以將這個(gè)方法進(jìn)行封裝:
function getType(value) { let type = typeof value; if (type !== 'object') { // 如果是基本數(shù)據(jù)類型,直接返回 return type; } // 如果是引用數(shù)據(jù)類型,再進(jìn)一步判斷,正則返回結(jié)果 return Object.prototype.toString.call(value).replace(/^\[object (\S+)\]$/, '$1'); } getType(123); // number getType('xxx'); // string getType(() => {}); // function getType([]); // Array getType({}); // Object getType(null); // Null
【相關(guān)推薦:javascript視頻教程、web前端】
The above is the detailed content of Let's talk about the difference between typeof and instanceof. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

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 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.

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

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

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 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).

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
