DIV CSS 佈局教程網

JS 型別判定實戰:陣列、函式、物件怎麼判斷最可靠
編輯:關於JavaScript     

typeof 很好用,但它有幾個眾所皆知的坑:typeof null 回傳 'object'、陣列也是 'object'。要準確分辨型別,得搭配 Object.prototype.toString。

一、判斷陣列

ES5 提供了原生方法 Array.isArray(IE9+ 支援)。若需兼顧更舊的環境,可用 Object.prototype.toString.call() 替代:

var isArray = Array.isArray || function (obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
};

isArray([1, 2]);            // true
isArray('not array');       // false

為什麼不用 instanceof Array?因為它在跨 iframe、跨 frame 的物件上會失效——不同 window 有各自的 Array 建構函式,原型鏈不通。Array.isArray 與 toString 都不受此影響,這也是前者成為標準的原因。

二、判斷函式

最簡單也效能最好的方式是 typeof obj == 'function'。但某些舊版瀏覽器存在 bug(例如把正則表達式誤判為函式),最保險的做法同樣是 toString:

var isFunction = function (obj) {
  return Object.prototype.toString.call(obj) === '[object Function]';
};

// 針對已知有 bug 的環境做特判,退回 typeof 以取得效能
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
  isFunction = function (obj) { return typeof obj == 'function'; };
}

要留意的是 toString 對 async 函式、generator 會回傳 [object AsyncFunction]、[object GeneratorFunction],若需要涵蓋這些情況要另外處理。

三、判斷物件

JavaScript 中「複雜型別就是物件」,而函式本質上也是物件。用 typeof 分別會得到 'object' 與 'function'。此外還必須排除 null,因為 typeof null === 'object':

var isObject = function (obj) {
  var type = typeof obj;
  return type === 'function' || (type === 'object' && !!obj);
};

isObject({});          // true
isObject(function(){}); // true
isObject(null);        // false   ← 關鍵
isObject([]);          // true(陣列也是物件)

四、最通用的解法

上面三種判斷其實可以統一,這也是許多工具函式庫採用的做法:

function typeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

typeOf([]);            // "array"
typeOf({});            // "object"
typeOf(null);          // "null"
typeOf(/re/);          // "regexp"
typeOf(new Date());    // "date"
typeOf(function(){});  // "function"
typeOf(123);           // "number"

這個技巧的原理是:不同型別的物件在 toString 時會產生不同的內部標籤([[Class]]),而這個標籤無法被使用者覆寫,因此比 constructor 可靠得多。

五、實務建議

今天的專案如果不是要支援 IE8 以下的古董環境,請直接這樣寫就好:

  • 陣列:Array.isArray(x)
  • 函式:typeof x === 'function'
  • 純物件:x !== null && typeof x === 'object' && !Array.isArray(x)
  • 其他:需要泛用判斷時用 Object.prototype.toString.call(x)
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved