萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 判斷資料類型完全指南:typeof、instanceof、constructor、Object.prototype.toString

四大判斷方法對比

方法基本型別引用型別null/undefined備註
typeof✅ 精確❌ 全是 "object"null→"object"
undefined→"undefined"
最快、最常用
instanceof❌ 報錯✅ 原型鏈判斷❌ 報錯檢測建構函數 prototype
constructor✅ (包裝物件)✅ 但可被篡改❌ 無屬性指向建構函數
Object.prototype.toString.call()✅ 精確✅ 精確 [object Type]✅ 精確最可靠、通用

詳細用法與陷阱

1. typeof

typeof true              // "boolean"
typeof 123               // "number"
typeof "str"             // "string"
typeof Symbol()          // "symbol"
typeof undefined         // "undefined"
typeof null              // "object" ← 著名 Bug
typeof {}                // "object"
typeof []                // "object"
typeof function(){}      // "function"
typeof new Date()        // "object"

適用:基本型別 + function 判斷。

2. instanceof

[] instanceof Array           // true
[] instanceof Object          // true (原型鏈向上)
new Date() instanceof Date    // true
new Date() instanceof Object  // true
function(){} instanceof Function // true

// 陷阱:跨 iframe/window 原型鏈斷裂
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const iArray = iframe.contentWindow.Array;
[] instanceof iArray // false!不同全域環境

適用:同一全域環境下判斷具體建構函數(Array、Date、自定義類)。

3. constructor

(123).constructor === Number      // true (自動包裝)
"str".constructor === String        // true
[].constructor === Array            // true
({}).constructor === Object          // true
new Date().constructor === Date     // true

// 陷阱:可被修改
function Foo() {}
const f = new Foo();
f.constructor = Bar; // 竄改
f.constructor === Foo // false

適用:快速獲取建構函數名稱(obj.constructor.name),但不可信任安全性。

4. Object.prototype.toString.call() —— 黃金標準

const toString = Object.prototype.toString;

toString.call(123)           // "[object Number]"
toString.call("str")         // "[object String]"
toString.call(true)          // "[object Boolean]"
toString.call(undefined)     // "[object Undefined]"
toString.call(null)          // "[object Null]"
toString.call({})            // "[object Object]"
toString.call([])            // "[object Array]"
toString.call(function(){})  // "[object Function]"
toString.call(new Date())    // "[object Date]"
toString.call(/regex/)       // "[object RegExp]"
toString.call(new Error())   // "[object Error]"
toString.call(Math)          // "[object Math]"
toString.call(JSON)          // "[object JSON]"
toString.call(arguments)     // "[object Arguments]"
toString.call(document)      // "[object HTMLDocument]"
toString.call(new Map())     // "[object Map]"
toString.call(new Set())     // "[object Set]"
toString.call(new Promise()) // "[object Promise]"

封裝通用 typeOf 函數

function typeOf(val) {
    if (val === null) return "null";
    if (val === undefined) return "undefined";
    const type = typeof val;
    if (type !== "object") return type;
    // 引用型別:用 toString 精確判斷
    return toString.call(val).slice(8, -1).toLowerCase(); // "array", "date", ...
}

// 測試
typeOf(null)        // "null"
typeOf([])          // "array"
typeOf(new Date())  // "date"
typeOf(/re/)        // "regexp"
typeOf(async function(){}) // "function" (async function 仍是 function)

特殊場景判斷

陣列判斷:Array.isArray()(ES5 標準)

Array.isArray([])           // true
Array.isArray(new Array())  // true
Array.isArray({})           // false
// 跨 iframe 也正常工作

純物件判斷(Plain Object)

function isPlainObject(obj) {
    if (!obj || toString.call(obj) !== "[object Object]") return false;
    const proto = Object.getPrototypeOf(obj);
    return proto === null || proto === Object.prototype;
}

isPlainObject({})              // true
isPlainObject(Object.create(null)) // true (無原型)
isPlainObject(new Foo())       // false
isPlainObject([])              // false

Promise/Thenable 判斷

function isThenable(val) {
    return val && typeof val.then === "function";
}

總結建議

  1. 基本型別 + function:typeof
  2. null/undefined:直接 === 比較
  3. 陣列:Array.isArray()
  4. Date/RegExp/Error 等內建型別:Object.prototype.toString.call()
  5. 自定義類實例:instanceof(同一全域環境)
  6. 通用工具函數:封裝 typeOf() 統一入口
copyright © 萬盛學電腦網 all rights reserved