判断数据是否为指定类型
函数体
// data:Any 待检验的数据// dataType:String 检验格式,例:String,Array,Object,Number,Null,Undefined,Boolean// dataType无需关心大小写,会自动转化,您只需关心是否正确输入export function getDataType(data, dataType) {if (Object.prototype.toString.apply(dataType) !== `[object String]`) { return };return Object.prototype.toString.apply(data) === `[object ${dataType.slice(0, 1).toUpperCase() + dataType.slice(1).toLowerCase()}]`;}
函数说明
1、判断当前参数是否为指定类型,是则返回true。反之,返回false。
2、常用于判断数据格式是否为指定格式,避免传入错误参数。
使用示例
let a = 1;let b = [];let c = {};let d = "a";let e = null;let f = undefined;let g = true;let h = NaN;// 无需关心dataType的大小写,以下示例均返回 trueconsole.log(this.getDataType(a, "Number"));console.log(this.getDataType(a, "nUmBer"));console.log(this.getDataType(b, "Array"));console.log(this.getDataType(b, "arRAy"));console.log(this.getDataType(c, "Object"));console.log(this.getDataType(d, "String"));console.log(this.getDataType(e, "Null"));console.log(this.getDataType(f, "Undefined"));console.log(this.getDataType(f, "uNdeFined"));console.log(this.getDataType(g, "Boolean"));console.log(this.getDataType(h, "Number"));
判断是否为空Object或空Array
函数体
// data:Array、Object 待检验的数据export function isEmptyObject(data) {let i;for (i in data) {if (Object.prototype.hasOwnProperty.call(data, i)) {return !1;}}return !0;}
函数说明
1、判断当前参数是否为空Object或者空Array,是则返回true。反之,返回false。
2、常用于判断数据是否为空数据,避免传入错误参数。
使用示例
let i = { name: "小明" };let j = {};let k = [];let l = [1, 2];console.log(this.isEmptyObject(i)); // falseconsole.log(this.isEmptyObject(j)); // trueconsole.log(this.isEmptyObject(k)); // trueconsole.log(this.isEmptyObject(l)); // false
