使用typeof可判断基本类型,但null会误判为”object”;Object.prototype.toString能精确识别所有内置类型;instanceof适用于检测自定义对象和继承关系;综合策略是先用typeof处理原始类型,再用toString细分对象类型,结合instanceof和null的特殊判断实现精准类型检测。
在JavaScript中,由于语言的动态特性,判断变量类型需要根据不同场景选择合适的方法。typeof、instanceof、Object.prototype.toString 等方法各有用途,但只有组合使用才能做到精确判断。
使用 typeof 处理基本类型
typeof 适合判断原始类型,但有局限性:
- string、number、boolean、undefined、function、symbol 能正确识别
- null 会错误返回 “object”
- 对象、数组、日期等都返回 “object”
示例:
typeof "hello" // "string" typeof 42 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof function(){}// "function" typeof null // "object"(注意!) typeof [] // "object"
用 Object.prototype.toString 获取精确类型标签
这是最可靠的方式,能区分所有内置类型:
立即学习“Java免费学习笔记(深入)”;
Object.prototype.toString.call([]) // "[object Array]" Object.prototype.toString.call(new Date) // "[object Date]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(42) // "[object Number]" Object.prototype.toString.call(/regex/) // "[object RegExp]"
可以封装一个通用函数:
function getType(value) { return Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); } // 使用 getType([]) // "array" getType(null) // "null" getType(123) // "number" getType(new Map) // "map"
instanceof 判断自定义对象和继承关系
适用于检测对象是否是某个构造函数的实例,特别适合自定义类:
[] instanceof Array // true new Date() instanceof Date // true {} instanceof Object // true
注意:跨iframe时可能失效,因为不同上下文的构造函数不相等。
综合判断策略
实际开发中建议结合多种方式:
- 先用 typeof 快速判断原始类型
- 对 object 类型再用 toString 进一步细分
- 涉及类实例时使用 instanceof
- null 单独判断(value === null)
基本上就这些,关键是根据需求选择合适的方法组合。
相关标签:
javascript java JavaScript String Boolean Object NULL 封装 构造函数 变量类型 继承 number undefined symbol function 对象 typeof prototype iframe