主要的4个方法
- Object.prototype.toString.call()
- typeof
- instanceof
- constructor
其他特定类型方法
- Array.isArray()
- Number.isNaN() 比 isNaN() 更准确
Object.prototype.toString.call()
最准确,可以判断所有情况
- 返回
[object type]格式的字符串
Object.prototype.toString.call(1)
typeof 运算符
- 只能处理
基本类型(除null 返回的是 Object)
- 返回类型的
字符串
- 缺点:
不能区分引用类型(Object/Array/Date/RegExp)
typeof 30
typeof Symbol()
typeof BigInt(1)
instanceof 运算符
- 主要检查构造函数的prototype是否在对象的
原型链上
- 返回
布尔值
- 缺点:
- 不能检测基本类型;
- 原型链可能被修改,导致不可靠;
- 跨全局环境(iframe),不可靠;
[] instanceof Array
new Date instanceof Date
new RegExp instanceof RegExp
constructor 构造函数
Array.isArray
Array.isArray([])