DIV CSS 佈局教程網

JS 檢測數據類型的四種方法:從 typeof 到 Object.prototype.toString
編輯:JavaScript基礎知識     

「這個變量到底是什麼類型」是 JS 面試與實戰中的高頻問題。可用的手段有四種,精準度與適用範圍各不相同,逐一來看。

方法一:typeof

typeof 用來檢測基本數據類型,返回值是包含類型名稱的字符串。

typeof value;
// 可能返回:"number"、"string"、"boolean"、"undefined"、"object"、"function"

兩個致命局限:

typeof null;              // "object" —— 歷史遺留缺陷
typeof [12, 23];          // "object" —— 數組無法識別
typeof /^$/;              // "object" —— 正則無法識別

也就是說,typeof 判斷不了數組,也判斷不了正則,凡是引用類型一律返回 "object"。

還有一個小細節:多個 typeof 連用時,返回值恆為 "string",因為第一次運算已把結果變成字符串了。

typeof typeof typeof [12, 23];   // "string"

方法二:instanceof 與 constructor

instanceof 檢測某個實例是否屬於某個類,它彌補了 typeof 無法識別引用類型的短板。

[] instanceof Array;      // true
/^$/ instanceof RegExp;   // true
[] instanceof Object;      // true ← 這裡就暴露了問題

constructor 可以避開「用 Object 檢測也是 true」的困擾:

[].constructor === Array;    // true
[].constructor === Object;    // false
({}).constructor === Object;  // true

instanceof 的三個局限

1. 原型鏈上能找到即為 true。instanceof 沿著 __proto__ 鏈向上查找,只要目標類在鏈上,結果就是 true:

var oDiv = document.getElementById("div1");
// 原型鏈:HTMLDivElement → HTMLElement → Element → Node → EventTarget → Object
oDiv instanceof HTMLDivElement;   // true
oDiv instanceof Node;             // true
oDiv instanceof Object;           // true

2. 基本數據類型不能用 instanceof 檢測。

1 instanceof Number;   // false

3. 原型繼承場景下結果不準確。這是最容易誤判的一點:

function Fn() {}
Fn.prototype = new Array;    // Fn 繼承了 Array
var f = new Fn;
f instanceof Array;          // true

但 f 實際上並沒有 length 屬性和數字索引,它只是個普通實例,本質上不是數組。之所以返回 true,僅僅是因為 f 的原型鏈上能找到 Array。原型繼承讓 instanceof 喪失了精確性。

補充:字面量與 new 的區別

對引用類型而言,兩種創建方式沒有實質差別,都是所屬類的實例。

var ary = [];
var ary = new Array;

但對基本類型,兩者不同:

var num1 = 1;
var num2 = new Number("1");
typeof num1;   // "number"
typeof num2;   // "object" ← 裝箱後變成對象

字面量創建的是基本類型值,實例方式創建的是對象。這也是為什麼不建議用 new String、new Number 的原因。

方法三:Object.prototype.toString.call()

這是最精準、最通用的方案。原理是借調 Object 原型上的 toString 方法,並把方法內的 this 改為待檢測的值。

Object.prototype.toString.call(12);          // "[object Number]"
Object.prototype.toString.call("zhufeng");   // "[object String]"
Object.prototype.toString.call([]);          // "[object Array]"
Object.prototype.toString.call(/^$/);        // "[object RegExp]"
Object.prototype.toString.call(null);        // "[object Null]"
Object.prototype.toString.call(undefined);   // "[object Undefined]"
Object.prototype.toString.call(new Date());  // "[object Date]"
Object.prototype.toString.call(Math);        // "[object Math]"

為什麼要用 call 借用

toString 是一個把值轉為字符串的方法,每個類的原型上都有自己的 toString:Number.prototype、String.prototype、Array.prototype 上的 toString 都是「把當前數據轉為字符串」,唯有 Object.prototype.toString 是用來返回值的所屬類信息的。

var obj = {};
obj.toString();   // "[object Object]"
// 執行過程:找到原型上的 toString 並執行,方法內 this 為 obj,
// 返回 "[object 當前 this 的直屬類]"

null 與 undefined 所屬類的原型上也有 toString,只是不允許直接訪問,因此必須通過 call 借用 Object 上的實現。

HTML 元素對象的原型鏈很長,但只有最底層的 Object.prototype 上才有 toString,所以 oDiv.toString() 實際調用的也是 Object.prototype.toString。

順帶解釋一個常見現象:alert 與 document.write 都是先把內容轉為字符串再輸出,所以 alert([]) 得到空字符串、alert(true) 得到 "true",而 alert({}) 會走 Object.prototype.toString。

方法四:封裝成通用 isType 工具

有了 toString 這個抓手,可以封裝一個通用的類型判斷函數:

/**
 * @param value 待檢測的值
 * @param type  期望的類型名
 */
function isType(value, type) {
  var res = Object.prototype.toString.call(value);   // "[object Array]"
  return res === "[object " + type + "]";
}

isType([], "Array");     // true
isType(1, "String");     // false

進一步優化,用正則忽略大小寫:

function isType(value, type) {
  var reg = new RegExp("^\\[object " + type + "\\]$", "i");
  return reg.test(Object.prototype.toString.call(value));
}

批量生成類型判定方法

把常用類型做成一張表,循環生成一組語義化的判斷函數,掛到工具對象上:

~function () {
  var utils = {},
      numObj = {
        isNum: "Number",  isStr: "String",  isBoo: "Boolean",
        isNul: "Null",    isUnd: "Undefined",
        isObj: "Object",  isAry: "Array",   isFun: "Function",
        isReg: "RegExp",  isDate: "Date"
      },
      isType = function (outerArg) {
        return function (innerArg) {
          var reg = new RegExp("^\\[object " + outerArg + "\\]$", "i");
          return reg.test(Object.prototype.toString.call(innerArg));
        };
      };

  for (var key in numObj) {
    if (numObj.hasOwnProperty(key)) {
      utils[key] = isType(numObj[key]);
    }
  }
  window.$type = utils;
}();

$type.isAry([]);    // true
$type.isFun([]);    // false

用 IIFE 包裹的好處是 numObj 與 isType 都不洩露到全局,只暴露最終的 $type 對象。

四種方法如何選

方法能否識別數組/正則能否檢測基本類型適用場景
typeof不能能(null 除外)
instanceof能,但原型繼承下不準不能
constructor能,較準確不推薦
Object.prototype.toString.call()能,精準能,全部覆蓋

實務結論很清晰:

  • 判斷是否為 undefined 或 function,用 typeof 最直觀。
  • 判斷是否為數組,用 Array.isArray()(ES5 起提供,且能跨 iframe 正常工作)。
  • 需要一個通用、精準、可擴展的類型判定方案,用 Object.prototype.toString.call 封裝。
  • 涉及自定義類的繼承關係判斷,才考慮 instanceof,並記住它在原型繼承下的失真風險。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved