型別

型別檢查 在 JavaScript

1 個練習

關於 型別檢查

了解一筆資料的型別是什麼,對於程式碼能否順利、無誤地執行,往往非常重要。

JavaScript 有幾種方法可以檢查值或物件的型別。

Note

JavaScript 的型別檢查機制有時不太可靠。

若想要更好的型別安全與更嚴謹的型別,你或許應該改用 TypeScript,這是一門以 JavaScript 為基礎、但採用靜態型別語言型別語法的語言。

typeof運算子

typeof運算子會回傳其運算元的型別。 輸出結果是一個字串,對應到其中一種原始資料型態的名稱,"null"除外。 它也可能是"function"或"object"。

typeof undefined;
// => "undefined"

typeof true;
// => "boolean"

typeof 42;
// => "number"

typeof 'Hello, World!';
// => "string"

typeof function () {
  return 'Hello, World';
};
// => "function"

typeof [1, 2, 3, 4];
// => "object"

typeof { city: 'Stockholm', country: 'Sweden' };
// => "object"

這是出於[歷史因素][typeof null is "object"]。

instanceof運算子

要檢查物件的型別,可以使用instanceof運算子。 它會根據第二個運算元是否包含在第一個運算元的原型鏈中,得出一個boolean。 更明確地說,instanceof會回傳第一個運算元是否為第二個運算元、或其子類別的實例。 instanceof只能用於物件。

class Beverage {
  // ...
}

// The Coffee class is a child of the Beverage class.
class Coffee extends Beverage {
  // ...
}

const java = new Coffee();

java instanceof Coffee;
// => true

java instanceof Beverage;
// => true
Advanced

Array類別有一個名為Array.isArray()的方法,用來檢查它的引數是否為陣列。

對於在不同領域中建立的陣列(例如網頁裡的iframe),instanceof Array不會有作用,但Array.isArray()可以。

這是因為 Array 類別在每個領域中都有不同的建構函式,而且每個iframe都有自己的領域,這表示原型鏈中的函式會不同,導致instanceof Array失敗。 Array.isArray()能夠忽略這一點,因此只要情況允許就應該使用它。

它也能避開誤判:有些物件實際上並不是Array,只是原型鏈中帶有Array。

({ __proto__: Array.prototype }) instanceof Array
// => true

Array.isArray({ __proto__: Array.prototype })
// => false

in運算子

in運算子會回傳第一個運算元是否為第二個運算元的屬性。 它不會檢查該屬性是否已定義值。 即使屬性的值設為undefined,in仍然能偵測到。

class Coffee {
  constructor() {
    this.temperature = 'hot';
    this.isDarkMatter = undefined;
  }

  coolDown() {
    this.temperature = 'warm';
  }
}

const espresso = new Coffee();

'temperature' in espresso;
// => true

'color' in espresso;
// => false

'isDarkMatter' in espresso;
// => true
Note

對於繼承而來的屬性和方法,in也會回傳true。

"coolDown" in espresso
// => true

"constructor" in espresso
// => true

若要避免這種情況,請改用Object.hasOwn()

Object.hasOwn()函式

Object.hasOwn()方法會回傳指定的物件是否_擁有給定的屬性_(不是繼承而來,也不是方法)。

class Coffee {
  constructor() {
    this.temperature = 'hot';
  }

  coolDown() {
    this.temperature = 'warm';
  }
}
const cappuccino = new Coffee();

Object.hasOwn(cappucino, 'temperature');
// => true

Object.hasOwn(cappucino, 'constructor');
// => false

Object.hasOwn(cappucino, 'coolDown');
// => false
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 型別檢查