前端判断数据类型方法

法一:typeof

typeof undefined // "undefined"
typeof false // "boolean"
typeof 'aaa' // "string"
typeof 123 // "number"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
typeof function(){} // "function"

可以发现当数据是 object,array,null 时,全部返回 object 类型。所以这个判断方法不太好。

法二:instanceof

 instanceof 是通过检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

"aaa" instanceof String // false
new String("aaa") instanceof String // true
new Date() instanceof Date // true
({}) instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true

比较好用,但是也有一些小问题,比如 Array 和 Object 都出现在 [] 的原型链上,可能会将 [] 误认为 Object 类型。

法三:toString.call()  最靠谱

toString.call(undefined) // "[object Undefined]"
toString.call(false) // "[object Boolean]"
toString.call('aaa') // "[object String]"
toString.call(123) // "[object Number]"
toString.call({}) // "[object Object]"
toString.call([]) // "[object Array]"
toString.call(null) // "[object Null]"
toString.call(function(){}) // "[object Function]"

可以根据返回的字符串判断是哪种类型。

法四:constructor  比较常用

const flg = true;flg.constructor === Boolean // true
const aaa = 'aaa';aaa.constructor === String // true
const num = 123;num.constructor === Number // true
const obj = {};obj.constructor === Object // true
const arr = [];arr.constructor === Array // true
const fun = function(){};fun.constructor === Function // true

 但是这种方式仍然有个弊端,就是 constructor 所指向的的构造函数是可以被修改的。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值