js详细检测数据类型
由于typeof只能判断5中基本类型:即 “number”,”string”,”undefined”,”boolean”,”object”
对于数组、函数、对象来说并不能详细的检测出类型, 这里使用的是对象的一个原生扩展函数,用来更精确的区分数据类型。
详细的判断类型给出如下:
console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[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(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
console.log(Object.prototype.toString.call(new Person));//[object Object]
由此可进一步封装成自己需要的方法,需要时调用。
getType: function(j){
let type = Object.prototype.toString.call(j) , ret;
switch(type){
case '[object Function]':
ret = 'function';
break;
case '[object String]':
ret = 'string';
break;
case '[object Number]':
ret = 'number';
break;
case '[object Object]':
ret = 'object';
break;
case '[object Array]':
ret = 'array';
break;
default:
ret = false;
}
return ret;
},
测试类型
let data = ['xx','aa'];
console.log(this.getType(data))
// array