JavaScript中判断类型需根据场景选择方法:1. typeof适用于基本类型,但null、数组和对象均返回”object”;2. instanceof通过原型链判断引用类型实例,跨iframe可能失效;3. Object.prototype.toString最可靠,可精确识别所有内置类型,推荐封装使用;4. 辅助方法如Array.isArray专门判断数组,结合null和对象的特判逻辑更精准。综合运用效果最佳。

JavaScript 中判断类型主要依靠 typeof、instanceof、Object.prototype.toString 等方法。每种方式适用的场景不同,下面详细介绍。
1. 使用 typeof 判断基本类型
typeof 是最常用的方式,适合判断原始类型,但有局限性。
typeof "hello" → “string” typeof 123 → “number” typeof true → “boolean” typeof undefined → “undefined” typeof Symbol() → “symbol” typeof function(){} → “function”
注意:typeof null 返回 “object”,这是历史遗留 bug;数组和对象也都会返回 “object”,无法区分。
2. 使用 instanceof 判断引用类型
instanceof 用于检测对象是否是某个构造函数的实例,适合判断数组、日期等。
[] instanceof Array → true {} instanceof Object → true new Date() instanceof Date → true /abc/ instanceof RegExp → true
注意:instanceof 依赖原型链,跨 iframe 时可能失效,且不能判断原始类型。
3. 使用 Object.prototype.toString 获取精确类型
这是最可靠的方法,能准确识别所有内置类型。
调用该方法会返回格式为 [object Type] 的字符串。
Object.prototype.toString.call("hello") // [object String]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(new Date()) // [object Date]
可以封装一个通用函数:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
getType({}) // "object"
getType([]) // "array"
getType(null) // "null"
4. 其他辅助方法
针对特定类型,也可使用专用方法:
Array.isArray([]) → true(推荐判断数组) value === null 判断 null typeof value === 'object' && value !== null && !Array.isArray(value) 判断普通对象
基本上就这些。日常开发中,typeof 处理基础类型,Array.isArray 判断数组,Object.prototype.toString 用于精确识别,组合使用效果最好。
以上就是js如何对类型进行判断的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1539014.html
微信扫一扫
支付宝扫一扫