首先typeOf判断分析
typeof只能返回,string、number、boolean、undefined、object、functionnull、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
4万+

被折叠的 条评论
为什么被折叠?



