实现判断数据类型的函数

首先typeOf判断分析

  • typeof只能返回,stringnumberbooleanundefinedobject、function
  • null、array、Error等会被判为object
console.log(
    typeof 100, //"number"
    typeof 'abc', //"string"
    typeof false, //"boolean"
    typeof undefined, //"undefined"
    typeof null, //"object"
    typeof [1,2,3], //"object"
    typeof {a:1,b:2,c:3}, //"object"
    typeof function(){console.log('aaa');}, //"function"
    typeof new Date(), //"object"
    typeof /^[a-zA-Z]{5,20}$/, //"object"
    typeof new Error() //"object"
    typeof new Number(100), //'object'
    typeof new String('abc'),// 'string'
    typeof new Boolean(true),//'boolean'
);

解决方案:

Object.prototype.toString.call()的方法,最后再用正则把其中的[object ]替换掉

function typeOf (obj) {
  if (obj === null) return String(null)
  return typeof obj === 'object'
    ? Object.prototype.toString.call(obj).replace(/(\[object|\])/g, '').toLowerCase()
    : typeof obj
}
let obj = typeOf({})
let arr = typeOf([])
let number = typeOf(123)
let str = typeOf('hello')
let fun = typeOf(function fn () { })
let bool = typeOf(true)
let nul = typeOf(null)
let kong = typeOf(undefined)
console.log(obj, arr, number, str, fun, bool, nul, kong);   
// object  array number string function boolean null undefined            

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值