手动实现JavaScript全部数据类型监测

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); // true

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Ï
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值