前端 JS 经典:typeof 和 instanceof 区别

1. typeof

typeof 用于判断一个变量的数据类型,返回一个表示数据类型的字符串。可以对如下类型进行判断:undefined、boolean、number、string、bigint、symbol、function 和 object。对 null 的判断是'object',这是个历史遗留问题。

javascript 复制代码
typeof null; // 'object'
typeof undefined; // 'undefined'
typeof true; // 'boolean'
typeof 110; // 'number'
typeof "yqcoder"; // 'string'
typeof function () {}; // 'function'
typeof {}; // 'object'
typeof []; // 'object'
typeof 9007199254740999n; // 'bigint'
typeof Symbol(); // 'symbol'

2. instanceof

instanceof 用于判断一个对象是否属于某个类或者其父类的实例。如果对象是指定类的实例,则返回 true;否则返回 false。

javascript 复制代码
const time = new Date();
const reg = /^yqcoder$/;

time instanceof Date; // true
reg instanceof RegExp; // true

综上:typeof 用于判断基本数据类型和函数类型,而 instanceof 用于判断对象是否属于某个类的实例。

相关推荐
ShineWinsu1 小时前
对于Qt:QDial常见属性以及信号的解析
开发语言·c++·qt·gui·客户端·旋钮·qdial
Java后端的Ai之路3 小时前
RAG 还是 Agent 自主检索?Claude Code 删掉向量库之后,我把选型讲透了
开发语言·人工智能·prompt·agent·rag
starzy19904 小时前
深入理解Scala高阶函数:函数式编程核心
开发语言·scala
czq_26867194879 小时前
Python打卡第46天
开发语言·python
卸任9 小时前
Vibe coding工具使用心得
前端·ai编程
brien910 小时前
为什么模型标称 1M,Google Antigravity 聊到 256K 却突然失忆?我们给它做了个原生行内监控圆环
前端
修炼的dance10 小时前
录屏关键帧间隔多少合适?六档实测,2秒到10秒小了75.6%
前端
Lank_M11 小时前
关键帧从1秒拉到10秒,录屏小87.3%,摄像头小10.8%
前端
补码缩写11 小时前
用 ffprobe 拆录屏,八成字节在 29 个关键帧上
前端
百思不得小李11 小时前
一个复杂的动态表单是如何实现的
前端·设计模式