自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

類型檢查:typeof 和 instanceof 運(yùn)算符區(qū)別?

開(kāi)發(fā) 前端
有時(shí)我們需要在 JS 中檢查變量的類型,要怎么做?使用typeof運(yùn)算符以及instanceof來(lái)檢查實(shí)例類型。

智米們肯定知道,JS 是種弱類型語(yǔ)言,對(duì)變量的類型沒(méi)有限制。

例如,如果我們使用字符串類型創(chuàng)建了一個(gè)變量,后面又可以為同一變量分配一個(gè)數(shù)字:

  1. let message = 'Hello'; // 分配一個(gè)字符串  
  2. message = 14; // 分配一個(gè)數(shù)字 

這種動(dòng)態(tài)性為我們提供了靈活性并簡(jiǎn)化了變量聲明。

[[356783]]

不好方面,我們永遠(yuǎn)不能確保變量包含某種類型的值。例如,以下函數(shù)greet(who)需要一個(gè)字符串參數(shù),但是,我們可以使用任何類型的參數(shù)來(lái)調(diào)用該函數(shù):

  1. function greet(who) { 
  2.   return `Hello, ${who}!` 
  3.  
  4. greet('World'); // => 'Hello, World!' 
  5. // You can use any type as argument 
  6. greet(true);    // => 'Hello, true!' 
  7. greet([1]);     // => 'Hello, 1!' 

有時(shí)我們需要在 JS 中檢查變量的類型,要怎么做?

使用typeof運(yùn)算符以及instanceof來(lái)檢查實(shí)例類型。

1. typeof運(yùn)算符

在 JS 中,基本類型有 String、Number、Boolean和 Symbol 等。此外,還有函數(shù)、對(duì)象和特殊值undefined和null。

typeof是用于確定 expression 類型的運(yùn)算符:

  1. const typeAsString = typeof expression; 

expression 的計(jì)算結(jié)果是我們要查找的類型的值。expression 可以是變量myVariable,屬性訪問(wèn)器myObject.myProp,函數(shù)調(diào)用myFunction()或數(shù)字 14。

typeof expression,取決于expression的值,結(jié)果可能為:'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。

我們來(lái)看看typeof運(yùn)算符每種類型的情況:

A) String:

  1. const message = 'hello!'
  2. typeof message; // => 'string' 

B) Number:

  1. const number = 5
  2. typeof number; // => 'number' 
  3.  
  4. typeof NaN;    // => 'number' 

C) Boolean:

  1. const ok = true
  2. typeof ok; // => 'boolean' 

D) Symbol:

  1. const symbol = Symbol('key'); 
  2. typeof symbol; // => 'symbol' 

E) undefined:

  1. const nothing = undefined
  2. typeof nothing; // => 'undefined' 

F) Objects:

  1. const object = { name: 'Batman' }; 
  2. typeof object; // => 'object' 
  3.  
  4. const array = [1, 4, 5]; 
  5. typeof array; // => 'object' 
  6.  
  7. const regExp = /Hi/; 
  8. typeof regExp; // => 'object' 

G) Functions:

  1. function greet(who) { 
  2.   return `Hello, ${who}!` 
  3.  
  4. typeof greet; // => 'function' 

1.1 typeof null

如上我們看到的,用 typeof 判斷對(duì)象結(jié)果是 'object'。

但是,typeof null也會(huì)計(jì)算為'object'!

  1. const missingObject = null
  2. typeof missingObject; // => 'object' 

typeof null為'object'是 JS 初始實(shí)現(xiàn)中的一個(gè)錯(cuò)誤。

因此,在使用typeof檢測(cè)對(duì)象時(shí),需要另外檢查null:

  1. function isObject(object) { 
  2.   return typeof object === 'object' && object !== null; 
  3.  
  4. isObject({ name: 'Batman' }); // => true 
  5. isObject(15);                 // => false 
  6. isObject(null);               // => false 

1.2 typeof 和未定義的變量

雖然typeof expression通常決定于expression的類型,但也可以使用typeof來(lái)確定是否定義了變量。

  1. // notDefinedVar is not defined 
  2. notDefinedVar; // throws ReferenceError 

typeof有一個(gè)不錯(cuò)的屬性,當(dāng)typeof評(píng)估未定義變量的類型時(shí),不會(huì)引發(fā) ReferenceError 錯(cuò)誤:

  1. // notDefinedVar is not defined 
  2. typeof notDefinedVar; // => 'undefined' 

變量notDefinedVar沒(méi)有在當(dāng)前作用域內(nèi)定義。然而,typeof notDefinedVar不會(huì)拋出引用錯(cuò)誤,而是將結(jié)果計(jì)算為 'undefined'。

我們可以使用typeof來(lái)檢測(cè)是否未定義變量,如果typeof myVar === 'undefined' 為 true, 則 myVar 未定義。

2. instanceof 運(yùn)算符

使用 JS 函數(shù)的通常方法是通過(guò)在其名稱后添加一對(duì)括號(hào)來(lái)調(diào)用它:

  1. function greet(who) { 
  2.   return `Hello, ${who}!`; 
  3.  
  4. greet('World'); // => 'Hello, World!' 

greet('World')是常規(guī)函數(shù)調(diào)用。

JS 函數(shù)可以做更多的事情:它們甚至可以構(gòu)造對(duì)象!要使函數(shù)構(gòu)造對(duì)象,只需在常規(guī)函數(shù)調(diào)用之前使用new關(guān)鍵字:

  1. function Greeter(who) { 
  2.   this.message = `Hello, ${who}!`; 
  3.  
  4. const worldGreeter = new Greeter('World'); 
  5. worldGreeter.message; // => 'Hello, World!' 

new Greeter('World')是創(chuàng)建實(shí)例worldGreeter的構(gòu)造函數(shù)調(diào)用。

如何檢查 JS 是否使用特定構(gòu)造函數(shù)創(chuàng)建了特定實(shí)例?使用 instanceof 運(yùn)算符:

  1. const bool = object instanceof Constructor; 

其中object是對(duì)對(duì)象求值的表達(dá)式,而Constructor是構(gòu)造對(duì)象的類或函數(shù),instanceof計(jì)算為布爾值。

worldGreeter實(shí)例是使用Greeter構(gòu)造函數(shù)創(chuàng)建的,因此worldGreeter instanceof Greeter計(jì)算結(jié)果為true。

從ES6 開(kāi)始,可以使用 class 來(lái)定義對(duì)象。例如,定義一個(gè)類Pet,然后創(chuàng)建它的一個(gè)實(shí)例myPet:

  1. class Pet { 
  2.   constructor(name) { 
  3.     this.name = name; 
  4.   } 
  5.  
  6. const myPet = new Pet('Lily'); 

new Pet('Lily')是創(chuàng)建實(shí)例myPet的構(gòu)造調(diào)用。

由于myPet是使用Pet類構(gòu)造的-const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的結(jié)果為 true:

  1. myPet instanceof Pet; // => true 

但是,普通對(duì)象不是Pet的實(shí)例:

  1. const plainPet = { name: 'Zoe' }; 
  2. plainPet instanceof Pet; // => false 

我們發(fā)現(xiàn)instanceof對(duì)于確定內(nèi)置的特殊實(shí)例(如正則表達(dá)式、數(shù)組)很有用:

  1. function isRegExp(value) { 
  2.   return value instanceof RegExp; 
  3. isRegExp(/Hello/); // => true 
  4. isRegExp('Hello'); // => false 
  5.  
  6. function isArray(value) { 
  7.   return value instanceof Array; 
  8. isArray([1, 2, 3]); // => true 
  9. isArray({ prop: 'Val' }); // => false 

2.1 instanceof 和父類

現(xiàn)在,Cat 擴(kuò)展了父類Pet:

  1. class Cat extends Pet { 
  2.   constructor(name, color) { 
  3.     super(name); 
  4.     this.color = color; 
  5.   } 
  6.  
  7. const myCat = new Cat('Callie', 'red'); 

不出所料,myCat是Cat類的實(shí)例:

  1. myCat instanceof Pet; // => true 

但同時(shí),myCat也是基類Pet的一個(gè)實(shí)例:

  1. myCat instanceof Pet; // => true 

3. 總結(jié)

JS 是一種弱類型的語(yǔ)言,這意味著對(duì)變量的類型沒(méi)有限制。

typeof expression可以用來(lái)查看 expression 的類型,結(jié)果是可能是其中的一個(gè):'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。

typeof null的值為'object',因此使用typeof檢測(cè)對(duì)象的正確方法是typeof object ==='object'&& object!== null。

instanceof運(yùn)算符讓我們確定實(shí)例的構(gòu)造函數(shù)。如果object是Constructor的實(shí)例,則object instanceof Constructor為true。

本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。

 

責(zé)任編輯:趙寧寧 來(lái)源: 大遷世界
相關(guān)推薦

2025-02-07 00:12:34

C#編程as

2015-06-09 10:55:58

JavaScriptinstanceof運(yùn)

2025-01-24 08:32:00

運(yùn)算符C#

2023-03-01 15:18:01

JavaScripttypeof運(yùn)算符

2025-02-24 11:16:20

2009-06-21 13:48:05

ShellLinux運(yùn)算符

2016-08-03 17:23:47

javascripthtml前端

2010-03-05 10:04:38

Python運(yùn)算符

2023-11-01 08:08:47

PythonIS運(yùn)算符

2009-08-11 15:51:08

C#運(yùn)算符算術(shù)運(yùn)算符

2024-02-26 15:17:20

2015-12-24 10:05:39

JavaScripttypeofinstanceof

2013-08-15 16:48:39

.Net基礎(chǔ)

2017-05-11 16:38:07

javascript邏輯運(yùn)算符

2009-08-12 15:02:49

C#賦值運(yùn)算符簡(jiǎn)單賦值運(yùn)算符

2009-08-12 15:20:18

C#賦值運(yùn)算符復(fù)合賦值運(yùn)算符

2021-10-19 22:23:05

typeof方式Instanceof

2021-05-09 22:00:59

TypeofInstanceof運(yùn)算符

2023-04-10 08:58:13

C#關(guān)系運(yùn)算符

2009-11-18 09:02:55

PHP運(yùn)算符
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)