js数据类型监测的方法
- typeof — 返回值是字符串,有”number”,”boolean”,”string”,”undefined”,”function”,”object”
缺点: 不能区分数组,对象,正则,因为返回的都是”object” - instanceof — 检测一个实例是否属于某个类
缺点:执行在当前原型链上的类型都会返回true - constructor — 检测基本数据类型
缺点:若把类的原型进行重写,若覆盖掉,检测结果就不准确 - Object.prototype.toString.call() — 最全面的方式
批量生产判断数据类型的方法 , 实际函数变量私有化
JS实现
function isType() {
const utilsType = {};
const types = ['String', 'Number', 'Boolean', 'Array', 'Object', 'Null', 'Undefined', 'Function', 'RegExp'];
for (let i = 0; i < types.length; i++) {
const type = types[i];
utilsType['is' + type] = (target) => Object.prototype.toString.call(target) === `[object ${type}]`;
}
return utilsType;
}
const utilsType = isType();
let flag = utilsType.isString('1');
console.log(flag);
TS实现
interface IsType {
isString: (arg: any) => boolean;
isNumber: (arg: any) => boolean;
isBoolean: (arg: any) => boolean;
isArray: (arg: any) => boolean;
isObject: (arg: any) => boolean;
isNull: (arg: any) => boolean;
isUndefined: (arg: any) => boolean;
isFunction: (arg: any) => boolean;
isRegEx: (arg: any) => boolean;
}Ï
// 批量生产判断数据类型的方法 , 实际函数变量私有化
function isType() {
const utilsType: IsType = {
isString: null,
isNumber: null,
isBoolean: null,
isArray: null,
isObject: null,
isNull: null,
isUndefined: null,
isFunction: null,
isRegEx: null,
};
const types = ['String', 'Number', 'Boolean', 'Array', 'Object', 'Null', 'Undefined', 'Function', 'RegExp'];
for (let i = 0; i < types.length; i++) {
// 创建一组私有的方法 用于验证制定数据是否为某一数据类型
const type = types[i];
utilsType['is' + type] = (target) => Object.prototype.toString.call(target) === `[object ${type}]`;
}
return utilsType;
}
export const utilsType: IsType = isType(); // 返回方法对象
utilsType.isArray([]) // true
utilsType.isString("") // true
utilsType.isNumber("") // falseÏ