function getType(value) {
if (value === null) {
return 'null';
}
const valueClass = Object.prototype.toString.call(value);
return valueClass.slice(8, -1).toLowerCase();
}
与 typeof 的对比:
| 值 | typeof 返回值 | getType 返回值 |
|---|---|---|
123 | 'number' | 'number' |
'hello' | 'string' | 'string' |
true | 'boolean' | 'boolean' |
null | 'object' | 'null' |
{} | 'object' | 'object' |
[] | 'object' | 'array' |
function(){} | 'function' | 'function' |
new Date() | 'object' | 'date' |
/regex/ | 'object' | 'regexp' |
1252

被折叠的 条评论
为什么被折叠?



