javascript类型判断需区分基本类型、引用类型和特殊值;typeof适用于基本类型和函数但对null误判为"object";object.prototype.tostring.call()最可靠,可精确识别内置对象类型;array.isarray()是判断数组首选;number.isnan()推荐检测nan。

JavaScript 中没有编译期类型检查,但可以通过运行时手段可靠判断动态数据的真实类型,关键在于区分 基本类型、引用类型 和 特殊值(如 null、NaN、undefined),避免仅依赖 typeof 的陷阱。
用 typeof 判断基本类型和函数
typeof 对字符串、数字、布尔、symbol、undefined 和 function 能准确返回字符串标识,但对 null 返回 "object"(历史遗留 bug),对数组、正则、日期等也统一返回 "object",所以它只适合初步筛查。
-
typeof "hello"→"string" -
typeof 42→"number" -
typeof true→"boolean" -
typeof undefined→"undefined" -
typeof null→"object"(⚠️ 错误!需单独处理) -
typeof []→"object"(无法区分数组)
用 Object.prototype.toString.call() 精确识别内置对象类型
这是最可靠的标准方法,能返回形如 "[object Array]"、"[object Date]" 的字符串,不受原型链污染影响,兼容性好。
-
Object.prototype.toString.call([])→"[object Array]" -
Object.prototype.toString.call(new Date())→"[object Date]" -
Object.prototype.toString.call(/abc/)→"[object RegExp]" -
Object.prototype.toString.call(null)→"[object Null]" -
Object.prototype.toString.call(undefined)→"[object Undefined]"
可封装为工具函数:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
// getType([1,2]) → "Array"
// getType(new Set()) → "Set"
结合 Array.isArray() 和 instanceof 处理特定场景
Array.isArray() 是判断数组的首选(比 toString 更语义化且性能略优);instanceof 适合检查自定义类或跨 iframe 的实例,但受原型链影响,不能用于基础类型或原始值。
-
Array.isArray([])→true(推荐) -
{} instanceof Object→true(但new String("x") instanceof String才是true,而"x" instanceof String是false) - 注意:
instanceof在不同全局环境(如 iframe)中可能失效,此时仍应优先用toString方法
安全检查 null、undefined 和 NaN
它们容易被忽略,但行为特殊:null 是独立类型(但 typeof 错报),undefined 表示未赋值,NaN 是唯一不等于自身的数值。
- 判空建议:
value === null或value == null(同时覆盖 null 和 undefined) - 严格区分 undefined:
value === undefined或使用typeof value === "undefined" - 检测 NaN:
Number.isNaN(value)(推荐),避免用value !== value或旧式isNaN()(会强制转换)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











