如何判断js的数据类型

如何判断js的数据类型

js数据类型

基本类型: String、Boolean、Number、null、undefined,Symbol
引用类型:Object、Function、Array

一共有6种方法

  1. typeof
  2. instanceof
  3. constructor
  4. Object.prototype.toString
  5. Array.isArray()
  6. 正则判断

1.typeof

typeof 可以对基本类型(除了null)进行判断

typeof 10 // number
typeof '张三' // string
typeof true // boolean
typeof undefined // undefined 
typeof null // object
typeof new Function() // function
typeof [] // object
typeof {} // object

2.instanceof

instanceof 检测的是原型 instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。

例 A instanceof B 判断 A 对象的原型链上是否有右边这个构造函数的 prototype 属性,返回一个布尔值

实现原理

instanceof(A, B) = {
  const a = A._proto_
  const b = B.prototype
  return a === b ? true : false
}

例:

[] instanceof Array // true
[] instanceof Object // true

3.constructor

constructor 判断方法跟 instanceof 相似,但是 constructor 检测 Object 与 instanceof 不一样,constructor 还可以处理基本数据类型的检测,不仅仅是对象类型。

constructor 可以得知某个实例对象,到底是哪个构造函数产生的

let f = new F()
f.constructor === F // true

4.Object.prototype.toString

每个对象都有一个 toString() 方法

Object.prototype.toString.call('张三')   // [object String]
Object.prototype.toString.call(10)   // [object Number]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(new Function()) // [object Function]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(document) // [object HTMLDocument]
Object.prototype.toString.call(window) //[object Window]

5.Array.isArray()

Array.isArray() 用于确定传递的值是否是一个 Array, 返回值是布尔类型

6.正则判断

可以判断数组和对象

方法:

function myTypeof(data) {
       const str = JSON.stringify(data)
       if (/^{.*}$/.test(data)) {
           return 'object'
       }
       if (/^\[.*\]$/.test(data)) {
           return 'array'
       }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值