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

JavaScript 中判断类型主要依靠 typeof、instanceof、Object.prototype.toString 等方法。每种方式适用的场景不同,下面详细介绍。
typeof 是最常用的方式,适合判断原始类型,但有局限性。
typeof "hello" → "string"typeof 123 → "number"typeof true → "boolean"typeof undefined → "undefined"typeof Symbol() → "symbol"typeof function(){} → "function"注意:typeof null 返回 "object",这是历史遗留 bug;数组和对象也都会返回 "object",无法区分。
instanceof 用于检测对象是否是某个构造函数的实例,适合判断数组、日期等。
[] instanceof Array → true{} instanceof Object → truenew Date() instanceof Date → true/abc/ instanceof RegExp → true注意:instanceof 依赖原型链,跨 iframe 时可能失效,且不能判断原始类型。
这是最可靠的方法,能准确识别所有内置类型。
调用该方法会返回格式为 [object Type] 的字符串。
Object.prototype.toString.call("hello") // [object String]<br>
Object.prototype.toString.call([]) // [object Array]<br>
Object.prototype.toString.call(null) // [object Null]<br>
Object.prototype.toString.call(new Date()) // [object Date]
可以封装一个通用函数:
function getType(value) {<br>
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();<br>
}<br>
getType({}) // "object"<br>
getType([]) // "array"<br>
getType(null) // "null"
针对特定类型,也可使用专用方法:
Array.isArray([]) → true(推荐判断数组)value === null 判断 nulltypeof value === 'object' && value !== null && !Array.isArray(value) 判断普通对象基本上就这些。日常开发中,typeof 处理基础类型,Array.isArray 判断数组,Object.prototype.toString 用于精确识别,组合使用效果最好。
以上就是js如何对类型进行判断的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号