元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
执行上下文
▶
创建过程
变量对象
作用域链
This绑定
▶
执行阶段
执行栈机制
词法环境
闭包实现
▶
内存管理
▶
内存模型
堆栈结构
内存分配
内存泄漏
▶
回收机制
标记清除
引用计数
代际假说
▶
事件循环
▶
运行机制
调用栈解析
任务队列
微任务优先
▶
异步处理
Promise原理
Async/Await
Web Workers
▶
原型系统
▶
原型基础
原型链机制
__proto__属性
构造函数
▶
类继承
ES6类语法
继承实现
super关键字
▶
类型系统
▶
基础类型
类型检测
装箱拆箱
类型转换
▶
高级类型
Symbol特性
BigInt实现
类型数组
▶
作用域与闭包
▶
作用域体系
词法作用域
动态作用域
作用域链生成
▶
闭包机制
闭包存储结构
IIFE模式原理
内存泄漏防范
发布时间:
2025-03-22 11:49
↑
☰
# JavaScript类型检测详解 本文将深入讲解JavaScript中的类型检测机制,包括各种类型检测方法的原理、使用场景和最佳实践。 ## 基础类型检测 ### 1. typeof运算符 ```javascript class TypeofDemo { static demonstrate() { // 基础类型检测 console.log(typeof 42); // "number" console.log(typeof "hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof Symbol()); // "symbol" console.log(typeof 42n); // "bigint" // 特殊情况 console.log(typeof null); // "object" - 这是一个历史遗留bug console.log(typeof function(){}); // "function" console.log(typeof []); // "object" console.log(typeof {}); // "object" } } ``` ### 2. instanceof运算符 ```javascript class InstanceofDemo { static demonstrate() { class Animal {} class Dog extends Animal {} const dog = new Dog(); console.log(dog instanceof Dog); // true console.log(dog instanceof Animal); // true console.log(dog instanceof Object); // true // 数组检测 const arr = []; console.log(arr instanceof Array); // true console.log(arr instanceof Object); // true } } ``` ## 高级类型检测 ### 1. Object.prototype.toString方法 ```javascript class ToStringDemo { static demonstrate() { const toString = Object.prototype.toString; // 基础类型 console.log(toString.call(42)); // "[object Number]" console.log(toString.call("hello")); // "[object String]" console.log(toString.call(true)); // "[object Boolean]" console.log(toString.call(undefined)); // "[object Undefined]" console.log(toString.call(null)); // "[object Null]" // 复杂类型 console.log(toString.call([])); // "[object Array]" console.log(toString.call({})); // "[object Object]" console.log(toString.call(new Date())); // "[object Date]" console.log(toString.call(/regex/)); // "[object RegExp]" } } ``` ### 2. Array类型检测 ```javascript class ArrayCheckDemo { static demonstrate() { const arr = []; // 方法1: Array.isArray console.log(Array.isArray(arr)); // true // 方法2: instanceof console.log(arr instanceof Array); // true // 方法3: Object.prototype.toString console.log(Object.prototype.toString.call(arr) === '[object Array]'); // true // 特殊情况: 跨iframe的数组检测 const iframe = document.createElement('iframe'); document.body.appendChild(iframe); const iframeArray = iframe.contentWindow.Array; const arr2 = new iframeArray(); // 只有Array.isArray能正确检测跨iframe的数组 console.log(Array.isArray(arr2)); // true console.log(arr2 instanceof Array); // false } } ``` ## 自定义类型检测 ### 1. Symbol.toStringTag ```javascript class CustomTypeDemo { static demonstrate() { class MyClass { get [Symbol.toStringTag]() { return 'MyClass'; } } const obj = new MyClass(); console.log(Object.prototype.toString.call(obj)); // "[object MyClass]" } } ``` ### 2. 类型检测工具函数 ```javascript class TypeCheckUtils { static demonstrate() { // 类型检测工具函数 const typeCheck = { isString(value) { return typeof value === 'string'; }, isNumber(value) { return typeof value === 'number' && !isNaN(value); }, isBoolean(value) { return typeof value === 'boolean'; }, isNull(value) { return value === null; }, isUndefined(value) { return value === undefined; }, isFunction(value) { return typeof value === 'function'; }, isObject(value) { return value !== null && typeof value === 'object'; }, isArray(value) { return Array.isArray(value); }, isDate(value) { return value instanceof Date; }, isRegExp(value) { return value instanceof RegExp; }, isPrimitive(value) { return ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'symbol' || typeof value === 'bigint' || value === null || value === undefined ); } }; // 使用示例 console.log(typeCheck.isString("hello")); // true console.log(typeCheck.isNumber(NaN)); // false console.log(typeCheck.isObject([])); // true console.log(typeCheck.isPrimitive(42)); // true } } ``` ## 最佳实践 ### 1. 类型检测选择 ```javascript class BestPractices { static demonstrate() { // 1. 基础类型优先使用typeof function processValue(value) { if (typeof value === 'string') { return value.trim(); } if (typeof value === 'number') { return value.toFixed(2); } throw new TypeError('Expected string or number'); } // 2. 复杂类型优先使用instanceof function processDate(value) { if (value instanceof Date) { return value.getTime(); } throw new TypeError('Expected Date object'); } // 3. 需要精确类型时使用Object.prototype.toString function getExactType(value) { return Object.prototype.toString.call(value).slice(8, -1); } } } ``` ### 2. 类型检测注意事项 ```javascript class TypeCheckCaveats { static demonstrate() { // 1. null的检测 function isNull(value) { return value === null; } // 2. undefined的检测 function isUndefined(value) { return value === undefined || typeof value === 'undefined'; } // 3. NaN的检测 function isNaN(value) { return Number.isNaN(value); // 优于全局isNaN } // 4. 空对象检测 function isEmptyObject(obj) { return obj !== null && typeof obj === 'object' && Object.keys(obj).length === 0; } } } ``` ## 总结 JavaScript中的类型检测机制包括: 1. typeof运算符 - 适用于基本类型检测 2. instanceof运算符 - 适用于实例关系检测 3. Object.prototype.toString - 适用于精确类型检测 4. Array.isArray - 专门用于数组检测 在实际开发中,我们应该: 1. 根据具体场景选择合适的类型检测方法 2. 注意特殊值(null、NaN等)的检测 3. 考虑跨iframe等特殊情况 4. 封装通用的类型检测工具函数 5. 遵循类型检测的最佳实践