前端 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 用于判断对象是否属于某个类的实例。

相关推荐
这是个栗子6 小时前
git报错:Reinitialized existing Git repository in ...
前端·git·github
ghfdgbg6 小时前
15. Vue工程化 + ElementPlus
前端·javascript·vue.js
Onlyᝰ6 小时前
前端使用jscpd查项目重复率
前端
〝七夜5696 小时前
Jsp中动态include和静态include的区别
java·开发语言
古城小栈6 小时前
JS 中有 undefined 和 null 两个空值,还有谁!
javascript·ecmascript
木土雨成小小测试员6 小时前
Python测试开发之跨域请求
开发语言·python
努力进修6 小时前
【JavaEE初阶】告别小白!Java IO 流读写 + 文件操作实战
java·开发语言·java-ee
沐知全栈开发6 小时前
Vue3 Ajax(Axios)详解
开发语言
dllmayday6 小时前
QWidget上叠加半透明QML组件显示方案
开发语言·qt5
电子_咸鱼6 小时前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt