DIV CSS 佈局教程網

JavaScript 型別判斷全攻略:typeof、instanceof 與 isArray 的正確用法
編輯:關於JavaScript     

型別判斷是 JavaScript 面試與日常開發中的高頻考點,也是很多人寫了很多年代碼卻依然容易踩坑的地方。下面按照「原始型別 → 物件 → 函式 → 陣列 → 屬性」的順序,把各種類型的檢測方式梳理清楚。

一、五種原始型別

JavaScript 的原始型別共有五種:string、number、boolean、undefined、null。

var name = "Jack";
var age = 32;
var single = false;
var app;               // undefined

console.log(typeof name);   // string
console.log(typeof age);    // number
console.log(typeof single); // boolean
console.log(typeof app);    // undefined
console.log(typeof null);   // object(歷史遺留問題)

可以看到,除了 null 之外,其餘四種原始型別都能直接用 typeof 準確識別,因此分支判斷寫起來非常自然:

if (typeof name === "string") { name += "Zhang"; }
if (typeof age === "number") { age++; }
if (typeof single === "boolean" && single) { /* ... */ }
if (typeof app === "undefined") { app = {}; }

而 typeof null 永遠返回 "object",這是語言設計初期留下的歷史包袱。判斷 null 最可靠的寫法是用全等運算子:

if (el === null) { /* ... */ }

二、物件:改用 instanceof

JavaScript 的物件既包括內建物件(Date、RegExp、Error 等),也包括開發者自己定義的自訂化物件。(Function 與 Array 雖然同樣屬於內建物件,但因為特殊性質,留到後面單獨說明。)

這類物件無法再用 typeof 區分,因為結果一律是 "object":

console.log(typeof new Date());   // object
console.log(typeof new RegExp()); // object
console.log(typeof new Error());  // object
console.log(typeof new Person()); // object

正確做法是使用 instanceof:

var date = new Date();
var reg  = new RegExp();
var err  = new Error();
var me   = new Person();

if (date instanceof Date)   { var year = date.getFullYear(); }
if (reg  instanceof RegExp) { reg.test(...); }
if (err  instanceof Error)  { throw err; }
if (me   instanceof Person) { /* ... */ }

不過自訂化物件有個天生的限制:如果頁面裡存在 frameA 與 frameB,而兩個 frame 各自定義了一份 Person,那麼在 frameA 中建立的 me 物件傳到 frameB 之後,me instanceof Person 會變成 false。Function 和 Array 也有同樣的跨 frame 問題,這正是它們不建議用 instanceof 檢測的原因。

三、Function:typeof 可跨 frame

用 typeof 檢測函式不受 frame 影響,是最通用的做法:

var func = function () {};
if (typeof func === 'function') { /* ... */ }

但 IE8 及更早版本對 DOM 方法(宿主物件方法)會返回 "object",因此在需要兼容老 IE 的場景下,改用 in 判斷特性是否存在:

console.log(typeof document.getElementById);       // 老 IE 中為 object
console.log(typeof document.getElementsByTagName); // 老 IE 中為 object
console.log(typeof document.createElement);        // 老 IE 中為 object

// 更可靠的特性檢測
if ("getElementById" in document)       { /* ... */ }
if ("getElementsByTagName" in document) { /* ... */ }
if ("createElement" in document)        { /* ... */ }

四、Array:Object.prototype.toString

ES5 之前沒有原生方案,社群中最精準的做法是利用 Object.prototype.toString 對陣列會返回固定字串這一事實:

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

這個寫法既精確又優雅,被大量函式庫採用,最終在 ES5 中被標準化為 Array.isArray()。今天寫業務代碼,直接用 Array.isArray(arr) 即可,不必再自己實作。

歷史上還流傳過一些「取巧」的判斷方式,例如依賴陣列都有 sort 方法:

function isArray(arr) {
  return typeof arr.sort === "function";
}

這種寫法只要自訂物件也定義了 sort 方法就會誤判,僅能作為理解思路的參考,不建議用於正式專案。

五、屬性是否存在

只想確認屬性是否掛在實例本身上,應該用 hasOwnProperty;如果不介意屬性來自實例還是原型鏈,用 in 更簡潔。

var Person = { name: "Jack", age: 33 };

if ("name" in Person)             { /* true */ }
if (Person.hasOwnProperty("name")) { /* true */ }
var Person = function (name, age) {
  this.name = name;
  this.age  = age;
};
Person.prototype.location = "Shanghai";

var me = new Person("Jack", 33);

if ("location" in me)                { /* true,來自原型 */ }
if (me.hasOwnProperty("location"))   { /* false,不在實例上 */ }

以下幾種常見寫法都不夠嚴謹,因為屬性值本身可能就是 0、null 或 undefined,容易誤判:

if (object[propName])              // 屬性值為 0 / "" 時會誤判
if (object[propName] === null)     // 無法區分「不存在」與「值為 null」
if (object[propName] === undefined) // 無法區分「不存在」與「值為 undefined」

總結

  • typeof:string、number、boolean、undefined、function
  • ===:null
  • Array.isArray():陣列
  • instanceof:內建物件(Function、Array 除外)與自訂化物件
  • hasOwnProperty:屬性是否在實例上;不區分原型鏈時可用 in

把這幾條規則記住,日常開發中的型別判斷基本不會再出錯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved