DIV CSS 佈局教程網

JS 資料型別檢測:從 typeof 到 Object.prototype.toString
編輯:JavaScript基礎知識     

強型別語言用 typeof 就能判斷型別,但在 JavaScript 這個弱型別語言裡,typeof 有幾個著名的陷阱。本文從逐項測試出發,構造一個通用可靠的型別檢測函數。

一、typeof 能解決的與不能解決的

JavaScript 常見型別有 number、string、boolean、undefined、function、array、object、null。先試試 typeof:

console.log(typeof 9);              // "number"    ✓
console.log(typeof "string");       // "string"    ✓
console.log(typeof true);           // "boolean"   ✓
var u;
console.log(typeof u);              // "undefined" ✓
console.log(typeof function () {}); // "function"  ✓

前幾項都沒問題,但接下來就出狀況了:

var t = null;
console.log(typeof t);        // "object"  ✗ 應該是 null

var array = [];
console.log(typeof array);    // "object"  ✗ 無法區分陣列

var obj = {};
console.log(typeof obj);      // "object"  ✓

null、array、object 三者都被判成 "object",需要額外處理。

二、先處理 null

function type(o) {
  return (o === null) ? "null" : (typeof o);
}

null 用嚴格相等直接攔下來即可。

三、用 Object.prototype.toString 區分物件種類

關鍵技巧:借用 Object.prototype.toString,它會回傳形如 [object Xxx] 的字串:

var toString = Object.prototype.toString;

console.log(toString.apply([]));    // "[object Array]"
console.log(toString.apply({}));    // "[object Object]"
console.log(toString.apply(/^\s+/)); // "[object RegExp]"
console.log(toString.apply(new Date()));  // "[object Date]"

這招之所以可靠,是因為每個內建型別都有自己的 Symbol.toStringTag 或內部 [[Class]] 標記,toString 會如實反映出來。相較之下 instanceof 有兩個弱點:無法區分同一原型鏈上的兄弟型別,且跨 iframe 時建構函數不同會失效。

四、通用型別檢測函數

function typeOf(e) {
  var _toString = Object.prototype.toString;
  var _type = {
    "undefined":       "undefined",
    "number":          "number",
    "boolean":         "boolean",
    "string":          "string",
    "function":        "function",
    "[object RegExp]": "regex",
    "[object Array]":  "array",
    "[object Date]":   "date"
  };
  return _type[typeof e] || _type[_toString.call(e)] || (e ? "object" : "null");
}

先查 typeof 的結果,查不到再退回 toString 的結果,最後用 e 的真偽值判定 null。三層保險下來,基本型別、陣列、正則、日期、null 都能正確分辨。

五、Zepto 的寫法值得參考

Zepto.js 裡有一些相當巧妙的判斷手法:

var toString = ({}).toString;   // 用空物件字面量取 toString,簡潔

function isFunction(value) {
  return toString.call(value) == "[object Function]";
}

function isObject(value) {
  return value instanceof Object;
}

function isArray(value) {
  return value instanceof Array;
}

// 類陣列:不是真陣列,但有一個 number 型別的 length 屬性
function likeArray(obj) {
  return typeof obj.length == 'number';
}

其中最精彩的是 isPlainObject——判斷是否為「純物件」(字面量或 new Object 建立的):

function isPlainObject(value) {
  var key, ctor;

  // 不是 [object Object] 直接排除
  if (toString.call(value) !== "[object Object]") return false;

  // 取得該物件建構函數的原型
  ctor = (isFunction(value.constructor) && value.constructor.prototype);

  // 原型不存在,或原型上沒有 isPrototypeOf,回傳 false
  if (!ctor || !hasOwnProperty.call(ctor, 'isPrototypeOf')) return false;

  // 遍歷所有可列舉屬性
  for (key in value);

  // 若沒有任何自屬屬性,或至少有一個自屬屬性,即為純物件
  return key === undefined || hasOwnProperty.call(value, key);
}

它的原理是:class 建立的實例其 constructor.prototype 上會有 isPrototypeOf 這個繼承而來的方法,而字面量物件的原型鏈末端才是 Object.prototype。透過這個差異就能把兩者區分開。

六、現代寫法

ES2015 之後,有幾個更簡潔的方案:

// 用 constructor 名稱
[].constructor === Array;        // true

// 用 Array.isArray,標準且跨 iframe 安全
Array.isArray([]);               // true

// 用 typeof 判斷 null 之外的原始值
typeof null === 'object';        // true(歷史 bug,需另外判斷)

// ES2020 的可選鏈與空值合併
var name = user?.profile?.name ?? '未設定';

結論:新專案直接用 Array.isArray(),其他型別用 typeof 加 instanceof 組合即可。上面那套 typeOf 函數的價值在於理解「為什麼 typeof 不夠用」,以及 toString.call 這個技巧的原理。

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