JS中判断数据类型的方法

本文主要讲述JS中的数据类型以及一些判断这些数据类型方法

JS中的数据类型

JS中的数据类型分为基本类型和引用数据类型

  • 基本类型:数字(Number)、布尔(Boolean)、空(Null)、未定义(Undefined)、字符串(String)、Symbol

  • 引用数据类型:对象(Object)、数组(Array)、函数(Function)

判断数据类型

1. typeof

typeof 是一个操作符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,包括以下 7 种:numberbooleanstringobjectundefinedfunctionsymbol 等。

typeof 1 // 'number'
typeof true // 'boolean'
typeof 'a' // 'string'
typeof {} // 'object'
typeof function(){} // 'function'
let b
typeof b // 'undefined'
typeof Symbol() // 'symbol'
typeof new Date() // 'object'

// 无法判断数组和null
typeof [] // 'object'
typeof null // 'object'

2. instanceof

instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,返回 true,否则返回 false。

// typeof 和 instanceof 的区别
let a = new String('abc') 
typeof a === 'object'// true 只能判断a是一个对象
a instanceof String // true 能判断a是一个string类型的对象

// instanceof 的使用
function fn1() { 
}
Object instanceof Object // true
Function instanceof Function // true
Function instanceof Object // true
fn1 instanceof fn1 // false
fn1 instanceof Object // true
fn1 instanceof Function // true

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

3. constructor

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

1.constructor // ƒ Number() { [native code] }
1.constructor === Number // true
[].constructor // ƒ Array() { [native code] }
[].constructor === Array // true
'a'.constructor // ƒ String() { [native code] }
'a'.constructor === String // true
{}.constructor // ƒ Object() { [native code] }
{}.constructor === Object // true

注意:null和undefined没有constructor

4. Object.prototype.toString

toString是Object.prototype上的一个方法,表达式为:Object.prototype.toString.call(A) 该方法返回表示该对象的字符串 [object 类型]

Object.prototype.toString.call(1) // '[object Numer]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call('a') // '[object String]' 
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call({a:1}) // '[object Object]' 
Object.prototype.toString.call([1,'a']) // '[object Array]'
Object.prototype.toString.call(() => {}) // '[object Function]' 
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(new Date()) // '[object Date]'
Object.prototype.toString.call(Symbol(1)) // '[object Symbol]'

5. Array.isArray()

Array.isArray()用于确定传递的值是否是一个 Array。如果对象是 Array ,则返回true,否则为false。

Array.isArray([]) // true

6. 正则判断

我们可以把对象和数组转成一个字符串,这样就可以做格式判断,从而得到最终的类型。

function myTypeof(data) {
  const str = JSON.stringify(data)
  if (/^{.*}$/.test(str)) {
      return 'object'
  }
  if (/^\[.*\]$/.test(str)) {
      return 'array'
  }
}
myTypeof({}) // 'object'
myTypeof({}) // 'array'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值