判斷數組歷經 instanceof、constructor、Array.isArray 多代演進,Object.prototype.toString.call() 曾是跨框架最可靠方案,理解其原理有助於掌握 JS 類型系統本質。
ECMA-262 規定每個對象擁有內部屬性 [[Class]],標識對象類型(如 "Array", "Date", "RegExp")。Object.prototype.toString 算法:
this 的 [[Class]] 值。
2. 返回 "[object " + [[Class]] + "]"。
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(new Array()); // "[object Array]"
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
Function.prototype.toString 返回函數源代碼字符串,非類型標識。Array.prototype.toString 返回元素連接字符串(同 join())。Object.prototype.toString 讀取 [[Class]]。// 父頁
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const iArr = iframe.contentWindow.Array;
const arr = new iArr(1,2,3);
arr instanceof Array; // false ❌
arr.constructor === Array; // false ❌
Array.isArray(arr); // true ✅ (ES5+)
Object.prototype.toString.call(arr); // "[object Array]" ✅
// ES5 標準,引擎內部實現,性能最優、語義最清晰
Array.isArray([]); // true
// 兼容極舊環境(IE8-)的 Polyfill
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
const type = obj => Object.prototype.toString.call(obj).slice(8, -1);
type(new Date()); // "Date"
type(/re/); // "RegExp"
type(null); // "Null"
type(undefined); // "Undefined"
type(123); // "Number"
type('str'); // "String"
type(true); // "Boolean"
type({}); // "Object"
type([]); // "Array"
type(function(){}); // "Function"
Object.prototype.toString.call() 通過讀取內部 [[Class]] 實現精確類型識別,解決了 instanceof 跨框架失效、constructor 可竄改的問題。現代代碼首選 Array.isArray(),性能更優且語義明確;編寫 Polyfill 或庫代碼時,toString.call 仍是兜底方案。