js中判断变量类型的终极(通用)方法来了
2019-08-12 本文已影响0人
大兵_HERG
1.第一种
function typeFn (any) {
return Object.prototype.toString.call(any).slice(8, -1).toLowerCase();
}
//返回值为小写的["string", "number", "boolean", "undefined", "null", "object", "array", "function", "regexp"]任意一种
2.第二种
function getDataType (data){
const typeMap = {
'[object String]': 'string',
'[object Number]': 'number',
'[object Boolean]': 'boolean',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
'[object Array]': 'array',
'[object Function]': 'function'
}
return typeMap[Object.prototype.toString.call(data)]
}
//此方法更为直观一些