笔记–判断值得类型和驼峰转换
2022/12/11
今天看了一个开源项目 vue-element-plus-admin
主要看了一下utils目录下面的方法,看看大佬的代码,还是可以学到很多东西的
1、判断数据类型
const toString = Object.prototype.toString
export const is = (val: unknown, type: string) => {
return toString.call(val) === `[object ${type}]`
}
is(new Date(),'Date') //true
使用toString()
检测对象类型
可以通过toString()
来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString()
来检测,需要以 Function.prototype.call()
或者 Function.prototype.apply()
的形式来调用,传递要检查的对象作为第一个参数,称为thisArg
。
var toString = Object.prototype.toString;
toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
//Since JavaScript