JS 数据类型检测的方式

js 的数据类型检查通常有 typeofinstanceofconstructortoString 这四种方法

数据类型

在 JavaScript 中数据类型分为两大类, 基本数据类型引用数据类型

  • 基本数据类型:Undefined、Null、Boolean、Number、String、Symbol(ES6 新增)和 BigInt(ES10 新增);

    Symbol

    在对象中我们可以使用 symbol 函数生成的值当作属性名,因为该属性名是 Symbol 数据类型的,这表示该值是独一无二,避免与其它属性名发生冲突。

js 复制代码
let name = Symbol('name'); 
let obj={ 
    [name]:'小李',
    age: 18,
    job: '法师'
}

console.log(typeof Symbol('name')) // symbol

Symbol 作为键名,并不会被常规的方法遍历得到,例如 for...in、for...of、Object.keys(obj)、Object.values(obj)、Object.getOwnPropertyNames()。

可以遍历得到的,例如 Object.getOwnPropertySymbols()、Reflect.ownKeys()。

BigInt

是一种特殊的数字类型,它支持任意长度的整数,在 JavaScript 中可以表示任意大的整数。

我们可以在整数后面添加 n,或者使用 BigInt() 函数来创建。

js 复制代码
console.log(typeof BigInt('12521111111155')) // bigint
console.log(typeof 1236721111111n) // bigint
  • 引用数据类型:对象(Object)类型,是一组由键、值组成的无序集合;2、数组(Array)类型,是一组按顺序排列的数据的集合;3、函数(Function)类型,是一段具有特定功能的代码块。

typeof

typeof str 通常检测数据的基本类型, 但对引用类型数据判断的话,除function会被识别出来之外,像null、{}、数组都输出为 object。

js 复制代码
typeof null // 'object'
typeof undefined // 'undefined'
typeof 5 // 'number'
typeof '6' // 'string'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof {} // 'object'
typeof [] // 'object'

instanceof

obj instanceof Object 用于检测构造函数的原型属性是否出现在示例对象的原型链上,可以检测某个对象是否属于某个构造函数

js 复制代码
// 定义构建函数
let Person = function() {}
let man = new Person()
man instanceof Person // true
let person = new String('xxx')
person instanceof String // true
let str = 'string'
str instanceof String // false

//关于 instanceof 的实现原理,如下:
//顺着原型链去找,直到找到相同的原型对象,返回true,否则为false
function myInstanceof(left, right) {
    // 这里先用typeof来判断基础数据类型,如果是,直接返回false
    if(typeof left !== 'object' || left === null) return false;
    // getProtypeOf是Object对象自带的API,能够拿到参数的原型对象
    let proto = Object.getPrototypeOf(left);
    while(true) {                  
        if(proto === null) return false;
        if(proto === right.prototype) return true;//找到相同原型对象,返回true
        proto = Object.getPrototypeof(proto);
    }
}

constructor

constructor 属性返回对象的构造函数。

js 复制代码
let a = 1
let b = "123"
let c = true
console.log(a.constructor === Number)//true
console.log(b.constructor === String)//true
console.log(c.constructor === Boolean)//true

// 不会顺着原型链找
let arr = []
console.log(arr.constructor === Array)
console.log(arr.constructor === Object)

//缺点是可以随意更改constructor,例如
let arr = []
Array.prototype.constructor = 'a'  //更改constructor
console.log(arr.constructor === Array)//false

Object.prototype.toString.call

这个方法是最准确的检测数据类型的方法,这里的 toString 并不是转为字符串,而是返回当前实例所属的类信息的字符串。因为每个对象都有 toString 方法。

然后通过 call 将 this 指向要检测的 Object。

js 复制代码
let a = 123
console.log(Object.prototype.toString.call(a))//[object Number]

总结

  • typeof只能检测除null外的基本数据类型,对于数组、对象、正则等都返回为Object

  • instanceof不能检测基本数据类型,检测引用类型时会顺着原型链往上找,只要原型链上有的,都返回true,同时,可以随意更改原型链的指向,导致检测结果不准确

  • constructor可以检测基本数据类型,也能分辨出数组和对象,但是我们可以随意更改constructor的值,导致检测结果不准确

  • Object.prototype.toString.call(value)可以根据返回的信息准确的检测出被测数据的类型

相关推荐
拳打南山敬老院20 分钟前
Context 不是压缩出来的,而是设计出来的
前端·后端·aigc
用户30767528112724 分钟前
💡 从"傻等"到"流淌":我在AI项目中实现流式输出的血泪史(附真实代码+深度解析)
前端
bluceli25 分钟前
前端性能优化实战指南:让你的网页飞起来
前端·性能优化
SuperEugene27 分钟前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
没想好d28 分钟前
通用管理后台组件库-9-高级表格组件
前端
阿虎儿32 分钟前
React Hook 入门指南
前端·react.js
核以解忧1 小时前
借助VTable Skill实现10W+数据渲染
前端
WangHappy1 小时前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
李剑一1 小时前
要闹哪样?又出现了一款新的格式化插件,尤雨溪力荐,速度提升了惊人的45倍!
前端·vue.js
闲云一鹤1 小时前
Git LFS 扫盲教程 - 你不会还在用 Git 管理大文件吧?
前端·git·前端工程化