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 用于精确识别,组合使用效果最好。










