01. JavaScript 类型系统与判断方法解析
1. JavaScript 的基本数据类型
JavaScript 采用动态类型系统,包含以下 7 种基本类型(截至 ES2023):
原始类型:
undefined
:未定义值null
:空值boolean
:布尔值(true
/false
)number
:数字(含NaN
和Infinity
)string
:字符串symbol
(ES6+):唯一标识符bigint
(ES2020+):大整数
对象类型:
object
:包含数组、函数、日期等引用类型function
(typeof 特殊处理)
javascript
// 类型示例
console.log(typeof 42); // "number"
console.log(typeof 9007199254740991n); // "bigint"
console.log(typeof Symbol('id')); // "symbol"
2. 类型判断方法对比
1. typeof
运算符
- 适用场景:基本类型快速判断
- 特殊表现:javascript
typeof null // "object"(历史遗留问题) typeof [] // "object" typeof new Date() // "object" typeof function() {} // "function"
2. instanceof
运算符
- 原理:检查原型链
- 局限性:javascript
[] instanceof Array // true 'str' instanceof String // false(原始类型 vs 包装对象)
3. Object.prototype.toString
- 最可靠的类型检测方法:javascript
Object.prototype.toString.call([]) // "[object Array]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(undefined) // "[object Undefined]"
4. 专用检测方法
Array.isArray()
Number.isNaN()
vs 全局isNaN()
3. 类型判断注意事项
Null 检测的特殊性:
javascriptconst isNull = val => val === null;
包装对象陷阱:
javascripttypeof new String('test') // "object" typeof String('test') // "string"
跨窗口对象检测:
javascript// 不同 iframe 中的数组 frameArray instanceof Array // false
自定义对象识别:
javascriptclass MyClass {} const obj = new MyClass(); console.log(obj instanceof MyClass); // true
4. 通用类型判断函数实现
javascript
function getType(value) {
const type = typeof value;
if (type !== 'object') {
return type;
}
// 处理 null
if (value === null) {
return 'null';
}
// 通过对象 toString 检测
const typeStr = Object.prototype.toString.call(value);
return typeStr.slice(8, -1).toLowerCase();
}
// 测试用例
console.log(getType([])); // 'array'
console.log(getType(null)); // 'null'
console.log(getType(/regex/)); // 'regexp'
console.log(getType(42n)); // 'bigint'
5. 类型判断优化策略
组合检测方法:
javascriptfunction isPlainObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; }
性能优化:
ES6+ 类型检测:
javascriptconst isSymbol = val => typeof val === 'symbol'; const isBigInt = val => typeof val === 'bigint';
6. 特殊场景处理
NaN 检测:
javascriptfunction isRealNaN(val) { return Number.isNaN(val); }
Promise 检测:
javascriptfunction isPromise(obj) { return !!obj && typeof obj.then === 'function'; }
浏览器环境检测:
javascriptfunction isElement(node) { return node instanceof HTMLElement; }
掌握准确的类型判断需要理解 JavaScript 的类型系统特性,建议:
- 优先使用
Object.prototype.toString
进行对象类型判断 - 对基本类型使用
typeof
快速检测 - 特殊值(如
null
、NaN
)使用专用检测方法 - 注意包装对象和原始类型的差异