1.typeof()
console.log(typeof bool); //boolean
console.log(typeof num);//number
console.log(typeof str);//string
console.log(typeof und);//undefined
console.log(typeof nul);//object
console.log(typeof arr);//object
console.log(typeof obj);//object
console.log(typeof fun);//function
console.log(typeof s1); //symbol
typeof可以识别出基本类型boolean,number,undefined,string,symbol,但是不能识别null。不能识别引用数据类型,会把null、array、object统一归为object类型,但是可以识别出function。
2.instanceof
console.log(bool instanceof Boolean);// false
console.log(num instanceof Number);// false
console.log(str instanceof String);// false
console.log(und instanceof Object);// false
console.log(nul instanceof Object);// false
console.log(arr instanceof Array);// true
console.log(obj instanceof Object);// true
console.log(fun instanceof Function);// true
console.log(s1 instanceof Symbol);// false
instanceof不能识别出基本的数据类型 number、boolean、string、undefined、unll、symbol。
但是可以检测出引用类型,如array、object、function。
3.Object.prototype.toString.call
console.log(Object.prototype.toString.call(bool));//[object Boolean]
console.log(Object.prototype.toString.call(num));//[object Number]
console.log(Object.prototype.toString.call(str));//[object String]
console.log(Object.prototype.toString.call(und));//[object Undefined]
console.log(Object.prototype.toString.call(nul));//[object Null]
console.log(Object.prototype.toString.call(arr));//[object Array]
console.log(Object.prototype.toString.call(obj));//[object Object]
console.log(Object.prototype.toString.call(fun));//[object Function]
console.log(Object.prototype.toString.call(s1)); //[object Symbol]
Object.prototype.toString.call方法检测是最全最准的
4.类型判断函数封装
checkType(obj) {
let Type = {};
"Boolean Number String Function Array Date RegExp Object Error Symbol".split(" ")
.forEach(e => (Type ["[object " + e + "]"] = e.toLowerCase()));
if (obj == null) return String(obj);
return typeof obj === "object" ? Type [Object.prototype.toString.call(obj)] || "object" : typeof obj;
}
网友评论