第一次写文章,写的不好,如有错误,望大神指出,本菜鸟感激不尽
最简单的判断类型的方法
- typeof 用于判断基本数据类型
- instanceof 用与判断引用数据类型
下面给出判断结果(大神可忽略)
console.log(typeof '数据类型') //string
console.log(typeof 1) //number
console.log(typeof true) //boolean
console.log(typeof undefined) //undefined
console.log(typeof Symbol()) //symbol
console.log(typeof {}) //object
console.log(typeof null) // object
console.log(typeof function(){}) // object
console.log([] instanceof Array) //true
由此可见typeof只能判断基本数据类型,那null也是基本数据类型,怎么typeof结果怎么是object,因为null是个空指针,所以typeof结果就成object。通过instanceof判断数组等引用数据类型。
那么除了上述方法,还有其他方法可以判断吗,当然是有的。Object.prototype.toString(),例如:
console.log(Object.prototype.toString.call('数据类型')) //[object String]
console.log(Object.prototype.toString.call(1)) //[object Number]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(Symbol())) //[object Symbol]
console.log(Object.prototype.toString.call(null)) //[object Null]
console.log(Object.prototype.toString.call(function(){})) //[object Function]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call({})) //[object Object]
看到上方得到的结果,是不是发现规律了返回的形式都是:[object xxxx],这里就知道如何去判断了吧。
接下来就写一个判断方法:
function checkType(obj) {
var class2Type = {};
var typeStr = "Boolen,Number,String,Null,Undefined,Symbol,Function,Array,Date,RegExp,Object,Error"
typeStr.split(',').map(item=> {
class2Type["[object " + item + "]"] = item.toLowerCase();
});
return typeof obj === "object" || typeof obj === "function"
? class2Type[Object.prototype.toString.call(obj)] || 'object' : typeof obj
}
如有错误,欢迎指教,谢谢!!