js数据类型判断

有三种方式,分别为 typeof、instanceof 和Object.prototype.toString.call()
一、typeof
使用方法 :(typeof + 值 ) --返回一个字符串

// 基本数据类型
typeof	'banana'	// 'string'
typeof	true		// 'boolean'
typeof	123			// 'number'
typeof	Symbol()    // 'symbol'
typeof	null		// 'object' 无法判定是否为 null
typeof	undefined	// 'undefined'
// 引用数据类型
typeof	 {}           // 'object'
typeof	 []           // 'object'
typeof	(() => {})    // 'function'

typeof方法判断数据类型不够精准
二、instanceof
使用方法:(值) instanceof (数据类型)–返回一个布尔值

[] instanceof	Array			// true
({}) instanceof	Object			// true
(()=>{}) instanceof	Function	// true

instanceof也是有缺陷的

let arr = []
let obj = {}
arr instanceof	Array// true
arr instanceof	Object// true
obj instanceof	Object// true
obj instanceof	Array// false

因为Object 构造函数在 arr 的原型链上 arr也判断为对象
三、Object.prototype.toString()

Object.prototype.toString.call({})              // '[object Object]'
Object.prototype.toString.call([])              // '[object Array]'
Object.prototype.toString.call(() => {})        // '[object Function]'
Object.prototype.toString.call('banana')        // '[object String]'
Object.prototype.toString.call(123)               // '[object Number]'
Object.prototype.toString.call(true)            // '[object Boolean]'
Object.prototype.toString.call(Symbol())        // '[object Symbol]'
Object.prototype.toString.call(null)            // '[object Null]'
Object.prototype.toString.call(undefined)       // '[object Undefined]'

Object.prototype.toString.call(newDate())      // '[object Date]'
Object.prototype.toString.call(Math)            // '[object Math]'
Object.prototype.toString.call(newSet())       // '[object Set]'
Object.prototype.toString.call(newWeakSet())   // '[object WeakSet]'
Object.prototype.toString.call(newMap())       // '[object Map]'
Object.prototype.toString.call(newWeakMap())   // '[object WeakMap]'

使用的时候封装一下

// $1表示括号里面的小正则 1表示匹配到的第一个
var type = function(data) {
      var toString = Object.prototype.toString;
      var dataType = toString
              .call(data)
              .replace(/\[object\s(.+)\]/, "$1")
              .toLowerCase()
      return dataType
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值