数据类型
数据类型
Breezli数据类型+类型判断
JavaScript数据类型分为基本类型与引用类型。
基本类型包括undefined、null、boolean、number、string、symbol(ES6)、bigint(ES11);
引用类型为object(如数组、函数等)。
类型判断方法如下:
typeof:返回类型字符串,但typeof null返回"object"(历史遗留问题),且无法区分数组与对象(均返回"object")。instanceof:检测对象原型链是否包含构造函数(如[] instanceof Array为true),但跨全局环境(如iframe)时失效。Object.prototype.toString.call():精确返回[object Type]格式(如数组返回"[object Array]"),可识别所有内置类型(包括null返回"[object Null]")。Array.isArray():专用于判断数组,避免instanceof的跨环境问题。
示例对比:
typeof 42→"number"typeof {}→"object"Object.prototype.toString.call(null)→"[object Null]"Array.isArray([])→true
总结:
- 基本类型优先用
typeof(注意null特例)。 - 精确类型用
Object.prototype.toString.call()。 - 数组判断用
Array.isArray()。 - 自定义对象需结合构造函数或
Symbol.toStringTag。




