typeof 是否能正确判断类型?
参考答案
大部分可以,但有明确缺陷:
typeof 1 // 'number'
typeof 'a' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof Symbol() // 'symbol'
typeof 1n // 'bigint'
typeof function(){} // 'function'
typeof {} // 'object'
typeof [] // 'object' ← 无法区分数组
typeof null // 'object' ← 历史 bug
typeof new Date() // 'object' ← 无法区分具体对象类型
补充
- 数组用
Array.isArray; - 具体对象类型用
Object.prototype.toString.call(x); - 类实例用
instanceof或constructor; - 未声明变量用 typeof 是安全的(返回 'undefined')。
结论:typeof 适合判断基本类型与 function,不适合判断引用类型细分。