js判断数据类型最准确的方法之一
function getType(data) { const type = Object.prototype.toString.call(data); let res = ''; switch (type) { case '[object Object]': res = 'Object'; break; case '[object Array]': res = 'Array'; break; case '[object String]': res = 'String'; break; case '[object Number]': res = 'Number'; break; case '[object Undefined]': res = 'Undefined'; break; case '[object Null]': res = 'Null'; break; case '[object Function]': res = 'Function'; break; case '[object Boolean]': res = 'Boolean'; break; case '[object Symbol]': res = 'Symbol'; break; case '[object BigInt]': res = 'BigInt'; break; default: break; }
return res;
}
console.log('getType({}): ', getType({})); console.log('getType([]): ', getType([])); console.log('getType("123"): ', getType('123')); console.log('getType(123): ', getType(123)); console.log('getType(): ', getType()); console.log('getType(null): ', getType(null)); console.log('getType(()=>{}): ', getType(()=>{})); console.log('getType(true): ', getType(true)); console.log('getType(Symbol()): ', getType(Symbol())); console.log('getType(BigInt(123)): ', getType(BigInt(123)));
如果感觉switch case写法有点长,可以改成这样写比较简洁:
function getType(data) { const type = Object.prototype.toString.call(data); const typeMap = { '[object Object]': 'Object', '[object Array]': 'Array', '[object String]': 'String', '[object Number]': 'Number', '[object Undefined]': 'Undefined', '[object Null]': 'Null', '[object Function]': 'Function', '[object Boolean]': 'Boolean', '[object Symbol]': 'Symbol', '[object BigInt]': 'BigInt' }; return typeMap[type] ?? ''; }
青云直上三千码