当前位置: 首页 > news >正文

JavaScript判断数据的类型

注:纯手打,如有错误欢迎评论区交流!
转载请注明出处:https://blog.csdn.net/testleaf/article/details/147954653
编写此文是为了更好地学习前端知识,如果损害了有关人的利益,请联系删除!
本文章将不定时更新,敬请期待!!!
欢迎点赞、收藏、转发、关注,多谢!!!

目录

    • 一、typeof:判断基本类型
    • 二、instanceof:判断实例原型链
    • 三、Object.prototype.toString.call():终极方案
    • 四、专门方法判断特定类型
      • 1、判断数组
      • 2、判断 NaN
      • 3、判断 null 或 undefined
    • 五、ES6+ 新增类型判断
      • 1、Map/Set/WeakMap/WeakSet
      • 2、Promise
      • 3、自定义类
    • 六、特殊案例处理
      • 1、区分对象和数组
      • 2、判断纯对象(Plain Object)
    • 七、终极方案对比表
    • 八、实际应用示例
    • 九、总结

一、typeof:判断基本类型

​​特点​​:能识别基本类型(除 null 外),但对引用类型返回 object

typeof 'hello'      // 'string'
typeof 42           // 'number'
typeof true         // 'boolean'
typeof undefined    // 'undefined'
typeof Symbol()     // 'symbol'
typeof BigInt(10)   // 'bigint'
typeof function(){} // 'function'// 局限性
typeof null         // 'object' (历史遗留问题)
typeof []           // 'object'
typeof {}           // 'object'

二、instanceof:判断实例原型链

​​特点​​:检查对象是否是某个构造函数的实例(对基本类型无效)。

[] instanceof Array      // true
{} instanceof Object     // true
new Date() instanceof Date // true// 局限性
'abc' instanceof String  // false (基本类型不适用)
null instanceof Object   // false

三、Object.prototype.toString.call():终极方案

​​特点​​:精准识别所有类型(推荐)。

Object.prototype.toString.call('hello')   // '[object String]'
Object.prototype.toString.call(42)        // '[object Number]'
Object.prototype.toString.call(true)      // '[object Boolean]'
Object.prototype.toString.call(null)      // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call([])        // '[object Array]'
Object.prototype.toString.call({})        // '[object Object]'
Object.prototype.toString.call(/regex/)   // '[object RegExp]'
Object.prototype.toString.call(new Date())// '[object Date]'

封装成通用函数​​:

function getType(obj) {return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
getType([]) // 'array'
getType(null) // 'null'

四、专门方法判断特定类型

1、判断数组

Array.isArray([]) // true

2、判断 NaN

Number.isNaN(NaN) // true (注意:全局 isNaN() 会先尝试转数字)

3、判断 null 或 undefined

value === null      // 仅判断 null
value === undefined // 仅判断 undefined
value == null       // 同时判断 null 或 undefined

五、ES6+ 新增类型判断

1、Map/Set/WeakMap/WeakSet

Object.prototype.toString.call(new Map())    // '[object Map]'
Object.prototype.toString.call(new Set())    // '[object Set]'

2、Promise

Object.prototype.toString.call(Promise.resolve()) // '[object Promise]'

3、自定义类

class MyClass {}
Object.prototype.toString.call(new MyClass()) // '[object Object]' (需自定义 toStringTag)

六、特殊案例处理

1、区分对象和数组

function isObject(obj) {return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
}

2、判断纯对象(Plain Object)

function isPlainObject(obj) {return Object.prototype.toString.call(obj) === '[object Object]' &&Object.getPrototypeOf(obj) === Object.prototype;
}
isPlainObject({})     // true
isPlainObject([])     // false
isPlainObject(new Date()) // false

七、终极方案对比表

方法适用场景局限性
typeof基本类型(除 nullnull 返回 object
instanceof引用类型(检查构造函数)不适用于基本类型
Object.prototype.toString​​所有类型​​(最精准)
Array.isArray()仅判断数组仅适用于数组
=== null 或 === undefined精确判断 null/undefined仅适用于这两个值

八、实际应用示例

function typeCheck(value) {const type = Object.prototype.toString.call(value).slice(8, -1);switch (type) {case 'String':case 'Number':case 'Boolean':case 'Null':case 'Undefined':case 'Symbol':case 'BigInt':return type.toLowerCase();default:return type; // 'Array', 'Object', 'Date', 'RegExp' 等}
}typeCheck(null)      // 'null'
typeCheck([])        // 'Array'
typeCheck(new Date())// 'Date'

九、总结

1、​​基本类型​​:优先用 typeof(注意 null 的坑)。
​​2、引用类型​​:用 Object.prototype.toString.call()
​​3、数组​​:直接用 Array.isArray()
4、​​特殊值​​:nullundefined=== 严格判断。
5、​​ES6+ 类型​​:结合 toString 和专用方法(如 Promise.resolve())。

相关文章:

  • 配置wsl内核时出现Multimedia support下面没选项
  • 大疆无人机自主飞行解决方案局限性及增强解决方案-AIBOX:特色行业无人机巡检解决方案
  • Day24-元组、OS模块
  • 如何在Mac电脑上的VScode去配置C/C++环境
  • redis 命令大全整理
  • libmemcached库api接口讲解四
  • Android锁
  • 【RabbitMQ】路由模式和通配符模式的具体实现
  • Canvas知识框架
  • OPC UA + ABP vNext 企业级实战:高可用数据采集框架指南
  • FlashInfer - SparseAttention(稀疏注意力)只计算部分有意义的注意力连接,而非全部 token 对
  • 文件(文件夹时间戳修改)最后修改时间变更
  • python打卡day25@浙大疏锦行
  • promise的说明
  • Minimum MPDU Start Spacing in A-MPDU
  • Spring Cloud:构建云原生微服务架构的最佳工具和实践
  • WhaleTunnel 信创数据库适配能力全景图:打通国产数据生态的最后一公里
  • 【Linux】shell内置命令fg,bg和jobs
  • 缺乏自动化测试,如何提高测试效率
  • 剖析提示词工程中的递归提示
  • 浙能集团原董事长童亚辉被查,还是杭州市书法家协会主席
  • 足球少年郎7月试锋芒,明日之星冠军杯构建顶级青少年赛事
  • “75万买299元路由器”事件进展:重庆市纪委等三部门联合介入调查
  • “远践”项目启动公益生态圈,上海青少年公益力量蓬勃生长
  • SIFF动画单元公布首批片单:《燃比娃》《凡尔赛玫瑰》等
  • 睡觉总做梦是睡眠质量差?梦到这些事,才要小心