Object.prototype.toString()
可以识别的类型有:
// 以下是11种: var number = 1; // [object Number] var string = '123'; // [object String] var boolean = true; // [object Boolean] var und = undefined; // [object Undefined] var nul = null; // [object Null] var obj = {a: 1} // [object Object] var array = [1, 2, 3]; // [object Array] var date = new Date(); // [object Date] var error = new Error(); // [object Error] var reg = /a/g; // [object RegExp] var func = function a(){}; // [object Function]
除此之外还有:
console.log(Object.prototype.toString.call(Math)); // [object Math] console.log(Object.prototype.toString.call(JSON)); // [object JSON]
function a() { console.log(Object.prototype.toString.call(arguments)); // [object Arguments] } a(); Object.prototype.toString.call(Math) [object Math];
封装为判断函数
let classType = {}
"Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(' ').map(item => {
return classType['[object ' + item + ']'] = item.toLowerCase();
})
function type(obj) {
//这里是为了兼容IE浏览器,
//因为在IE中null和undefined会被Object.prototype.toString识别为object
if (obj === null) {
return obj + ''
}
return typeof obj === 'object' || typeof obj === 'function' ? classType[Object.prototype.toString.call(obj)] || "object" : typeof obj
}