「這個變量到底是什麼類型」是 JS 面試與實戰中的高頻問題。可用的手段有四種,精準度與適用範圍各不相同,逐一來看。
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 檢測某個實例是否屬於某個類,它彌補了 typeof 無法識別引用類型的短板。
[] instanceof Array; // true /^$/ instanceof RegExp; // true [] instanceof Object; // true ← 這裡就暴露了問題
constructor 可以避開「用 Object 檢測也是 true」的困擾:
[].constructor === Array; // true
[].constructor === Object; // false
({}).constructor === Object; // true
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 喪失了精確性。
對引用類型而言,兩種創建方式沒有實質差別,都是所屬類的實例。
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 原型上的 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]"
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。
有了 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() | 能,精準 | 能,全部覆蓋 |
實務結論很清晰:
Array.isArray()(ES5 起提供,且能跨 iframe 正常工作)。