实现一个函数,返回给定参数的数据类型的函数,并自定义类名,是什么类型的函数
参考答案
function typeOf(v, className) {
const t = Object.prototype.toString.call(v).slice(8, -1); // Null/Array/Date...
return className ? `${className}${t}` : t;
}
typeOf([]); // 'Array'
typeOf([], 'my'); // 'myArray'
要点:
typeof null是 'object',需用 toString 判别;- toString 能区分 Array/Date/RegExp/Map/Set/Promise/Error 等;
- 可被
Symbol.toStringTag伪造,生产可结合Array.isArray、instanceof; - 严格说是"工具函数/工厂函数(返回函数的函数)",也可写成柯里化的高阶函数。