首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript instanceof vs typeof:區別與用法

     編輯:程式設計疑難解答

核心區別

  • `typeof x`** 返回字符串,表示基本類型 (`"number"`, `"string"`, `"boolean"`, `"undefined"`, `"symbol"`, `"bigint"`, `"function"`) 或 `"object"` (null、數組、對象、正則等)。
  • `x instanceof Constructor`** 判斷 `x` 的原型鏈上是否存在 `Constructor.prototype`,返回布爾值。僅適用於對象 (引用類型)。

示例


typeof 123           // "number"
typeof "abc"         // "string"
typeof {}            // "object"
typeof []            // "object"
typeof null          // "object" (著名bug)
typeof function(){}  // "function"

[] instanceof Array  // true
[] instanceof Object // true
new Date() instanceof Date // true
new Date() instanceof Object // true
123 instanceof Number // false (基本類型)

使用建議

  • 判斷基本類型 → `typeof`。
  • 判斷數組 → `Array.isArray(arr)` (最準確)。
  • 判斷自定義類實例 → `instanceof`。
  • 判斷 null → `x === null`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved