一、基础概念对比
特性 | typeof |
instanceof |
---|---|---|
本质 | 一元运算符,返回基本类型字符串 | 二元运算符,检查对象的原型链归属 |
返回值 | 字符串(如 "number" 、"object" ) |
布尔值(true /false ) |
适用类型 | 基本类型(null 例外)和 function |
对象类型(对基本类型无效) |
历史遗留问题 | typeof null 返回 "object" |
无特殊问题,但受原型链完整性影响 |
二、核心功能差异
1. 检测范围
-
typeof
- 检测 基本数据类型:如
number
、string
、boolean
、undefined
、symbol
、bigint
。 - 对引用类型(如数组、对象、正则表达式)统一返回
"object"
。 - 例外:
typeof function(){}
返回"function"
。
typeof 123; // "number" typeof "hello"; // "string" typeof [1,2]; // "object"(无法区分数组) typeof new Date();
- 检测 基本数据类型:如