1. 程式人生 > 實用技巧 >JavaScript中的型別檢查有點麻煩

JavaScript中的型別檢查有點麻煩

js的動態型別有好有壞。好的一面,不必指明變數的型別。不好的是,咱們永遠無法確定變數的型別。

typeof運算子可以確定js中的6種類型:

typeof 10;        // => 'number'
typeof 'Hello';   // => 'string'
typeof false;     // => 'boolean'
typeof { a: 1 };  // => 'object'
typeof undefined; // => 'undefined'
typeof Symbol();  // => 'symbol'

同樣,instanceof運算子用於檢測建構函式的prototype屬性是否出現在某個例項物件的原型鏈上。

class Cat { }
const myCat = new Cat();

myCat instanceof Cat; // => true

但是typeof和instanceof的一些行為可能會令人混淆。防範於未然,咱們需要提前瞭解一些邊緣情況。

1. typeof null

typeof myObject === 'object'會告知myObject是否是一個物件型別。舉個例子:

const person = { name: '前端小智' };

typeof person; // => 'object'

typeof person是'object',因為person是一個普通的 JS 物件。

在某場景下,變數值可能需要指定為null,下面是一些場景:

  • 可以使用null來跳過指示配置物件
  • 使用null初始化稍後要儲存物件的變數
  • 當函式由於某種原因無法構造物件時,返回null

例如,如果不存在正則表示式匹配項,則str.match(regExp)方法返回null:

const message = 'Hello';
message.match(/Hi/); // => null

這裡引出一個問題,可以使用typeof 來區分有值的物件和具有null值的物件嗎?

let myObject = null;
typeof myObject; // => 'object'

myObject = { prop: 'Value' };
typeof myObject; // => 'object'

從上面可以看出,typeof物件有值的物件和具有null值的物件,得到的結果都是'object'。

可以如下面方法來檢測變數是否有物件且不是null:

function isObject(value) {
  return typeof value === 'object' && value !== null;
}

isObject({});   // => true
isObject(null); // => false

除了檢查value是否為object:typeof value === 'object'之外,還需要明確地驗證null:value !== null。

2. typeof array

如果試圖檢測一個變數是否包含一個數組,常見的錯誤就是使用typeof操作符:

const colors = ['white', 'blue', 'red'];

typeof colors; // => 'object'

檢測陣列的正確方法是使用Array.isArray():

const colors = ['white', 'blue', 'red'];
const hero = { name: 'Batman' };

Array.isArray(colors); // => true
Array.isArray(hero);   // => false

Array.isArray(colors)返回一個布林值true,表示colors是一個數組。

3.虛值型別檢查

JS中的undefined是一個特殊值,表示未初始化的變數。

如果試圖訪問未初始化的變數、不存在的物件屬性,則獲取到的值為undefined:

let city;
let hero = { name: '前端小智', villain: false };

city;     // => undefined
hero.age; // => undefined

訪問未初始化的變數city和不存在的屬性hero.age的結果為undefined。

要檢查屬性是否存在,可以在條件中使用object[propName],這種遇到值為虛值或者undefined是不可靠的:

function getProp(object, propName, def) {
  // 錯誤方式
  if (!object[propName]) {
    return def;
  }
  return object[propName];
}

const hero = { name: '前端小智', villain: false };

getProp(hero, 'villain', true);  // => true
hero.villain;                    // => false

如果物件中不存在propName,則object [propName]的值為undefined。if (!object[propName]) { return def }保護缺少的屬性。

hero.villain屬性存在且值為false。 但是,該函式在訪問villan值時錯誤地返回true:getProp(hero, 'villain', true)

undefined是一個虛值,同樣false、0和''和null。

不要使用虛值作為型別檢查,而是要明確驗證屬性是否存在於物件中:

  • typeof object[propName] === 'undefined'
  • propName in object
  • object.hasOwnProperty(propName)

接著,咱們來改進getProp()函式:

function getProp(object, propName, def) {
  // Better
  if (!(propName in object)) {
    return def;
  }
  return object[propName];
}

const hero = { name: '前端小智', villain: false };

getProp(hero, 'villain', true);  // => false
hero.villain;                    // => false

if (!(propName in object)) { ... }條件正確確定屬性是否存在。

邏輯運算子

我認為最好避免使用邏輯運算子||作為默情況,這個容易打斷閱讀的流程:

const hero = { name: '前端小智', villain: false };

const name = hero.name || 'Unknown';
name;      // => '前端小智'
hero.name; // => '前端小智'

// 不好方式
const villain = hero.villain || true;
villain;      // => true
hero.villain; // => false

hero物件存在屬性villain,值為false,但是表示式hero.villain || true結果為true。

邏輯操作符||用作訪問屬性的預設情況,當屬性存在且具有虛值時,該操作符無法正確工作。

若要在屬性不存在時預設設定,更好的選擇是使用新的雙問號(??)操作符,

const hero = { name: '前端小智', villan: false };

// 好的方式
const villain = hero.villain ?? true;
villain;      // => false
hero.villain; // => false

或使用解構賦值:

const hero = { name: '前端小智', villain: false };

// Good
const { villain = true } = hero;
villain;      // => false
hero.villain; // => false

4. typeof NaN

整數,浮點數,特殊數字(例如Infinity,NaN)的型別均為數字。

typeof 10;       // => 'number'
typeof 1.5;      // => 'number'
typeof NaN;      // => 'number'
typeof Infinity; // => 'number'

NaN是在無法建立數字時建立的特殊數值。NaN是not a number的縮寫。

在下列情況下不能建立數字:

Number('oops'); // => NaN

5 * undefined; // => NaN
Math.sqrt(-1); // => NaN

NaN + 10; // => NaN

由於NaN,意味著對數字的操作失敗,因此對數字有效性的檢查需要額外的步驟。

下面的isValidNumber()函式也可以防止NaN導致的錯誤:

function isValidNumber(value) {
  // Good
  return typeof value === 'number' && !isNaN(value);
}

isValidNumber(Number('Z99')); // => false
isValidNumber(5 * undefined); // => false
isValidNumber(undefined);     // => false

isValidNumber(Number('99'));  // => true
isValidNumber(5 + 10);        // => true

除了typeof value === 'number'之外,還多驗證!isNaN(value)確保萬無一失。

5.instanceof 和原型鏈

JS 中的每個物件都引用一個特殊的函式:物件的建構函式。

object instanceof Constructor是用於檢查物件的建構函式的運算子:

const object = {};
object instanceof Object; // => true

const array = [1, 2];
array instanceof Array; // => true

const promise = new Promise(resolve => resolve('OK'));
promise instanceof Promise; // => true

現在,咱們定義一個父類Pet和它的子類Cat:

class Pet {
  constructor(name) {
    this.name;
  }
}

class Cat extends Pet {
  sound = 'Meow';
}

const myCat = new Cat('Scratchy');

現在,嘗試確定myCat的例項

myCat instanceof Cat;    // => true
myCat instanceof Pet;    // => true
myCat instanceof Object; // => true

instanceof運算子表示myCat是Cat,Pet甚至Object的例項。

instanceof操作符通過整個原型鏈搜尋物件的建構函式。要準確地檢測建立物件的建構函式,需要檢測constructor屬性

myCat.constructor === Cat;    // => true
myCat.constructor === Pet;    // => false
myCat.constructor === Object; // => false

只有myCat.constructor === Cat的計算結果為true,表示Cat是myCat例項的建構函式。

廣州VI設計公司https://www.houdianzi.com

6. 總結

運算子typeof和instanceof用於型別檢查。 它們儘管易於使用,但需要注意一些特殊情況。

需要注意的是:typeof null等於'object'。 要確定變數是否包含非null物件,需要顯示指明null:

typeof myObject === 'object' && myObject !== null

檢查變數是否包含陣列的最佳方法是使用Array.isArray(variable)內建函式。

因為undefined是虛值的,所以我們經常直接在條件句中使用它,但這種做法容易出錯。更好的選擇是使用prop in object來驗證屬性是否存在。

使用雙問號操作系符號object.prop ?? def或者{ prop = def } = object來訪問可能丟失的屬性。

NaN是一個型別為number的特殊值,它是由對數字的無效操作建立的。為了確保變數有正確的數字,最好使用更詳細的驗證:!isNaN(number) && typeof number === 'number'。

最後,請記住instanceof通過prototype鏈搜尋例項的建構函式。如果不知道這一點,那麼如果使用父類驗證子類例項,可能會得到錯誤的結果。