最近工作中需要对获取的数据类型进行判断以进行相应的操作,网上学习了下,为了方便使用搞了个方法,如下:
/**
* @name: $determineType
* @cname: 判断类型
* @desc: 判断Javascript数据类型
* @param (*) datatype 传入要判断的数据
* @panme: datatype: undefined、null、boolean、number、string、object...
* @result: true or false
*/
export function $determineType() {
return {
isArray: (t) => Object.prototype.toString.call(t) === "[object Array]",
isNumber: (t) => Object.prototype.toString.call(t) === "[object Number]",
isString: (t) => Object.prototype.toString.call(t) === "[object String]",
isBoolean: (t) => Object.prototype.toString.call(t) === "[object Boolean]",
isObj: (t) => Object.prototype.toString.call(t) === "[object Object]",
isNull: (t) => Object.prototype.toString.call(t) === "[object Null]",
isUndefined: (t) => Object.prototype.toString.call(t) === "[object Undefined]",
isFunction: (t) => Object.prototype.toString.call(t) === "[object Function]",
isDate: (t) => Object.prototype.toString.call(t) === "[object Date]",
isMoment: (t) => Object.prototype.toString.call(t) === "[object Object]" && t._isAMomentObject,
isDocument: (t) => Object.prototype.toString.call(t) === "[object Document]" || Object.prototype.toString.call(t) == "[object HTMLDocument]",
isRegExp: (t) => Object.prototype.toString.call(t) === "[object RegExp]",
isSymbol: (t) => Object.prototype.toString.call(t) === "[object Symbol]",
}
}
// 方法使用示例
// 引入方法
import { $determineType } from "~mixins/useUtils"
// 1.判断传入数据是否是数组类型
if ($determineType().isArray(proj.owner)) {
for (let i in proj.owner) {
owners.push(this.addProjectData[1].options[proj.owner[i]].label)
}
owners = owners.toString()
} else {
owners = proj.owner
}
// 2.判断传入数据是否是数字,然后进行相应转换
transProjLevel(val) {
return $determineType().isNumber(val) ? PROJECT_LEVEL.find(r => r.key === val)?.name : PROJECT_LEVEL.find(r => r.name === val)?.key
},参考: