首先我们都知道js判断类型可以通过 Object.prototype.toString.call() 方法;这个方法可以更准确的拿到它所对应的类型。那么我们可以把它封装一下!
let type = function(o) {
let t = Object.prototype.toString.call(o);
return t.match(/object (.*?)\]/)[1].toLowerCase()
}
console.log(type({})) // object
这样我就拿到该值所对应的类型了!但是,各位有没有发现既然能够这样,我们干嘛不封装一个方法放在全局供大家使用,很大程度上提高了我们的开发效率。好了那么请大家往下看!
let type = function(o) {
let t = Object.prototype.toString.call(o);
return t.match(/object (.*?)\]/)[1].toLowerCase()
}
let arr = ['Null','Undefined','Object','Array','String','Number','Boolean','Function',
'RegExp']
arr.forEach(function(item){
Object['is' + item] = function(o) {
return type(o) === item.toLowerCase()
}
});
console.log(Object.isNumber(21)) // true
console.log(Object.isObject(21)) // false
console.log(Object.isNull(null)) // true
这样我们后面想判断什么类型就可以直接拿使用Object.方法名 就可以判断出类型了。以上代码如有没看懂的小伙伴,欢迎下面评论区留言!