JS基础工具类——BASE

在实际的编码中,经常会用到一些空值判断之类的,太常用了,顺手就简单封装了一下。

 

直接上代码:

/**
 * 基础操作和定义
 */
var BASE = {
    /**
     * 日志级别:DEBUG-调试, INFO-信息, RESULT-重要结果, WARN-告警, ERROR-错误, NONE-不打印日志
     */
    logLevel: LOG_LEVEL.INFO,

    /**
     * 日志等级
     */
    LOG_LEVEL: LOG_LEVEL,

    /**
     * 日志打印控制相关操作
     */
    LOG: LOG,

    /**
     * 设置日志级别
     * @param {string} log_level 
     * 用法:
     * BASE.setLogLevel(BASE.LOGE_LEVEL.ERROR);
     */
    setLogLevel: function(log_level) {
        if (this.isNotEmpty(log_level) && 
            this.isKeyInObj(log_level.toUpperCase(), this.LOG_LEVEL)) {
            this.logLevel = this.getValueByKey(log_level.toUpperCase(), this.LOG_LEVEL);
        } else {
            // 传级别不符合条件的,当作DEBUG级
            this.logLevel = this.LOG_LEVEL.DEBUG;
        }
    },
    
    /**
     * 时间操作相关
     */
    TIME: TIME,
    
    
    
    // 公用方法
    /**
     * 判断对象是否为空
     * @param {*} obj 对象
     * @returns {boolean}
     */
    isNotNull: function(obj) {
        if (typeof obj == "number") {
            if (!isNaN(obj)) {
                return true;
            }
        } else if (typeof obj == "boolean") {
            if (obj != null && obj !== undefined) {
                if ((obj + '').toLowerCase() == "false" || (obj + '').toLowerCase() == "true") {
                    return true;
                }
            }
        } else {
            if (obj && obj != null && obj !== undefined) {
                return true;
            }
        }

        // this.LOG.debug(()=>{
        //     console.log('obj is null or undefined!');
        // });
        return false;
    },

    /**
     * 判断对象是否为空[适用于字符串、数组]
     * @param {*} obj 对象
     * @returns {boolean}
     */
    isNotEmpty: function(obj) {
        var result = false;
        if (this.isNotNull(obj)) {
            if (typeof obj == "string") {
                if (obj.length > 0) {
                    result = true;
                }
            } else if (typeof obj == "number") {
                result = true;
            } else if (typeof obj == "object") {
                if (obj instanceof Array) {
                    if (obj.length > 0) {
                        result = true;
                    }
                } else {
                    result = true;
                }
            } else {
                result = true;
            }

            // if (!result) {
            // 	this.LOG.debug(()=>{
            // 		console.log('obj is null or undefined or empty!');
            // 	});
            // }
        }
        return result;
    },

    /**
     * 判断对象是否为非空且非"null"
     * @param {*} obj 对象
     * @returns {boolean}
     */
    isNotNullStringAndNotEmpty: function(obj) {
        if (obj != 'null') {
            if (this.isNotEmpty(obj)) {
                return true;
            }
        }
        return false;
    },

    /**
     * 判断key是否在对象中
     * @param {string} key 键
     * @param {*} obj 对象
     * @returns {boolean}
     */
    isKeyInObj: function(key, obj) {
        if (this.isNotNull(obj)) {
            if (this.isNotEmpty(key)) {
                if (key in obj) {
                    return true;
                } else {
                    // this.LOG.debug(()=>{
                    // 	console.log('key:' + key + ' is not in obj!');
                    // });
                }
            } else {
                // this.LOG.debug(()=>{
                // 	console.log('key is null or undefined or empty!');
                // });
            }
        } else {
            // this.LOG.debug(()=>{
            // 	console.log('obj is null or undefined!');
            // }
        }
        return false;
    },
    
    /**
     * 获取非空对象(为空时返回default_value的值)
     * @param {*} obj 对象
     * @param {*} default_value 默认值(当对象为空时返回)
     * @returns {*}
     */
    getNotNull: function(obj, default_value) {
        if (this.isNotNull(obj)) {
            return obj;
        }
        return default_value;
    },

    /**
     * 获取非空数据[适用于字符串、数组](为空时,返回default_value的值)
     * @param {*} obj 对象
     * @param {*} default_value 默认值(当对象为空时返回)
     * @returns {*}
     */
    getNotEmpty: function(obj, default_value) {
        if (this.isNotEmpty(obj)) {
            return obj;
        }
        return default_value;
    },

    /**
     * 根据key获取value(key不存在时,返回default_value)
     * @param {string} key 键
     * @param {*} obj 对象
     * @param {*} default_value 默认值(当key不存在时,返回)
     * @returns {*}
     */
    getValueByKey: function(key, obj, default_value) {
        if (this.isKeyInObj(key, obj)) {
            return obj[key];
        }
        return default_value;
    },

    /**
     * 根据keys获取key-value(如果keys都不存在非空的值时,以keys中最后一个key返回default_value的值)
     * @param {array} keys 键
     * @param {*} obj 对象
     * @param {string} default_key 默认键(如果keys都不存在非空的值时,以keys中最后一个key返回)
     * @param {*} default_value 默认值(如果keys都不存在非空的值时,以keys中最后一个key返回default_value的值)
     * @returns {*} {key:value}
     */
    getKeyValueByKeys: function(keys, obj, default_key, default_value) {
        if (this.isNotEmpty(keys)) {
            let key = default_key;
            let value = default_value;
            for (var i = 0; i < keys.length; i++) {
                // 取最后一个
                value = this.getValueByKey(keys[i], obj);
                if (this.isNotNull(value)) {
                    key = keys[i];
                }
            }
            key = this.getNotEmpty(key, default_key);
            if (typeof value == "string") {
                value = this.getNotEmpty(value, default_value);
            } else {
                value = this.getNotNull(value, default_value);
            }
            return {key: key, value: value};
        }
        return {key: default_key, value: default_value};
    },

    /**
     * 将非空的对象原样返回,将空的对象转为默认值返回
     *   示例1:var tmp = objectFix(obj, '');
     *   示例2:var tmp = objectFix(obj, 0);
     *   示例3:var tmp = objectFix(obj, 0.00);
     * @param {*} obj 对象
     * @param {*} defaultValue 对象为空时要替换成的默认值
     * @returns {*}
     */
    objectFix: function(obj, defaultValue) {
        var value = defaultValue;
        if (this.isNotNull(obj)) {
            value = obj;
        }
        return value;
    },

    /**
     * 把字符串替换为指定的字符串
     * @param {*} obj 对象
     * @param {string} fixStr 修复的默认值
     * @returns {*}
     */
    stringFix: function(obj, fixStr) {
        var fix = "";
        if (this.isNotNull(fixStr)) {
            fix = fixStr;
        }
        var result = this.objectFix(obj, fix);
        if (!this.isNotEmpty(result) && this.isNotNull(fix)) {
            result = fix;
        }
        return result;
    },

    /**
     * 布尔型修复
     * @param {*} obj 对象
     * @param {*|boolean} defaultValue 修复的默认值
     * @returns {boolean}
     */
    boolFix: function(obj, defaultValue) {
        var fixValue = false;
        if (this.isNotNull(defaultValue)) {
            fixValue = defaultValue;
        }

        var value = this.objectFix(obj, fixValue);
        value = (obj + "").toLowerCase() == "true" ? true : false;

        return value;
    },

    /**
     * int型修复
     * @param {*} obj 对象
     * @param {*|int} defaultNum 修复的默认值
     * @returns {int}
     */
    intFix: function(obj, defaultNum) {
        var num = 0;
        if (this.isNotNull(defaultNum)) {
            num = defaultNum;
        }
        var value = this.objectFix(obj, num);
        return parseInt(value);
    },

    /**
     * 把浮点数保留几位小数点
     * 浮点型修复,空对象会转换成传入的fixNum位小数(fixNum没传入时会转换成两位小数,如:0.00)
     *  示例1:floatFix(obj, 2); //保留两位小数
     *  示例2:floatFix(obj, 0); //不保留小数,转换成整数
     *  示例3:floatFix(obj); //默认保留两位小数
     * @param {*} obj 对象
     * @param {*|int} fixNum 保留小数的位数,不传时默认为两位,为0时返回的是整数
     * @returns {*|number} 返回按指定保留小数位的浮点型数值(fixNum=0时,返回的是整数)
     */
    floatFix: function(obj, fixNum) {
        var value = 0.00;
        var fix = 2;
        if (this.isNotNull(fixNum)) {
            fix = parseInt(fixNum);
        }
        if (fix >= 0) {
            var tmp = this.objectFix(obj, 0.00);
            value = tmp * 1.00; //转带小数点的
            value = value.toFixed(fix);
        } else {
            value = this.intFix(obj);
        }
        return value;
    },

    /**
     * 从url中获取指定参数
     * @param {string} href url地址
     * @param {string} name 参数名称
     * @param {boolean} isDecode 是否decodeURIComponent解码(默认为解码:不存在 或 非false时,为false时不解码)
     * @returns {string} null/string
     */
    queryGetArguments: function(href, name, isDecode) {
        // 如果链接没有参数,或者链接中不存在我们要获取的参数,直接返回空
        if (href.indexOf('?') == -1 || href.indexOf(name + '=') == -1) {
            return null;
        }
        // 获取链接中参数部分
        var queryString = href.substring(href.indexOf('?') + 1);
        // 分离参数对 ?key=value&key2=value2
        var parameters = queryString.split('&');
        var pos, paraName, paraValue;
        for (var i = 0; i < parameters.length; i++) {
            // 获取等号位置
            pos = parameters[i].indexOf('=');
            if (pos == -1) {
                continue;
            }
            // 获取name 和 value
            paraName = parameters[i].substring(0, pos);
            paraValue = parameters[i].substring(pos + 1);

            if (paraName == name) {
                // console.log('-----queryGetArguments isDecode=' + isDecode);
                if (this.isNotNull(isDecode) && isDecode === false) {
                    let value = paraValue.replace(/\+/g, ' ');
                    if (this.isNotNullStringAndNotEmpty(value)) {
                        // this.LOG.debug(()=>{
                        //     console.log('-----queryGetArguments 不解码 name=' + name + ', value=' + value);
                        // });
                        return value;
                    } else {
                        // this.LOG.debug(()=>{
                        //     console.log('-----queryGetArguments 不解码 name=' + name + ', value=');
                        // });
                        return null;
                    }
                } else {
                    let value = decodeURIComponent(paraValue.replace(/\+/g, ' '));
                    if (this.isNotNullStringAndNotEmpty(value)) {
                        // this.LOG.debug(()=>{
                        //     console.log('-----queryGetArguments 解码 name=' + name + ', value=' + value);
                        // });
                        return value;
                    } else {
                        // this.LOG.debug(()=>{
                        //     console.log('-----queryGetArguments 解码 name=' + name + ', value=');
                        // });
                        return null;
                    }
                }
            }
        }
        return null;
    },

    /**
     * 解析对象的属性,组装成query字符串(只处理对象的,非对象的会返回空字符串)
     * 此方法只处理对象
     * 二级的如果对象或数组时会强转成json字符串且encodeURIComponent编码
     * @param {*} argObject 对象
     * @param {*} argIsEncode 是否encodeURIComponent编码(默认为false),控制一级的编码,二级的如果对象或数组时会强转成json字符串且encodeURIComponent编码
     * @returns {string} 返回query字符串(不符合转换的,则会返回空字符串)
     */
    parseObjectToUrlQuery: function(argObject, argIsEncode) {
        var query = '';
        if (this.isNotNull(argObject)) {
            if (typeof(argObject) === 'object') {
                for (var key in argObject) {
                    if (this.isNotNull(argIsEncode) && (argIsEncode + '').toLowerCase() === 'true') {
                        // 编码
                        let value = this.getValueByKey(key, argObject, '');
                        if (typeof(value) != 'string') {
                            value = JSON.stringify(value); // 将object转成json字符串
                            query += key + '=' + encodeURIComponent(value) + '&';
                        } else {
                            query += key + '=' + encodeURIComponent(value) + '&';
                        }
                    } else {
                        // 不编码
                        let value = this.getValueByKey(key, argObject, '');
                        if (typeof(value) != 'string') {
                            value = JSON.stringify(value); // 将object转成json字符串
                            query += key + '=' + encodeURIComponent(value) + '&';
                        } else {
                            query += key + '=' + value + '&';
                        }
                    }
                }
                if (query.endsWith('&')) {
                    query = query.substr(0, query.length - 1);
                }
            }
        }
        return query;
    },

    /**
     * 将对象的属性组装成get请求的query(aa=xxx&bb=xxx&cc=xxx)
     * 此方法兼容处理对象和json字符串(会转换成json对象再作解析处理)
     * 二级的如果对象或数组时会强转成json字符串且encodeURIComponent编码
     * @param {*} params 对象
     * @param {boolean} isEncode 是否encodeURIComponent编码(默认为false)
     * @returns {string} 返回query字符串(不符合转换的,则会返回空字符串)
     */
    objectToUrlQuery: function(params, isEncode) {
        var query = '';
        if (this.isNotNull(params)) {
            if (typeof(params) === 'object') {
                query = this.parseObjectToUrlQuery(params, isEncode);
            } else if (typeof(params) === 'string') {
                // 将string转json
                if (this.isNotEmpty(params)) {
                    try {
                        let tmpParams = JSON.parse(params);
                        query = this.parseObjectToUrlQuery(tmpParams, isEncode);
                    } catch(ex) {
                        this.LOG.error(()=>{
                            console.error(ex);
                        });
                    }
                }
            }
        }
        return query;
    },

    /**
     * 获取区间[begin:end]内的随机数
     * @param {number} begin 左区间值(最小数值)
     * @param {number} end 右区间值(最大数值)
     * @returns {number} 返回随机数
     */
    getRandomBetween: function(begin, end) {
        let min = begin;
        let max = end;
        if (begin > end) {
            min = end;
            max = begin;
        }
        return Number(Math.random() * (max - min + 1) + min);
    },

    /**
     * 获取指定长度的随机ID字符串
     * @param {number} len 随机ID字符串的长度(不包含tag,要小于36位)
     * @param {string} tag ID前缀(默认为没有)
     * @returns {string} 返回随机ID字符串
     */
    getRandomId: function(len, tag) {
        let rid = Number(Math.random().toString().substr(3, len) + Date.now()).toString(36);
        if (this.isNotEmpty(tag)) {
            rid = tag + '_' + rid;
        }
        return rid;
    },
    
};


 

如何使用?

// 打印日志相关
// 设置日志级别
BASE.setLogLevel(BASE.LOG_LEVEL.INFO);

// 打印日志(只有level为info级别的才会输出)
BASE.LOG.info(()=>{
    console.log('>> 打印info日志');
});
// 此日志不会输出
BASE.LOG.debug(()=>{
    console.log('>> 打印debug日志');
});



// 从对象中取值
let params = {
    width: 100,
    height: 200
};

let width = BASE.getValueByKey('width', params, -1);



// 判断对象是否不为空
let obj1 = null;
if (BASE.isNotNull(obj1) {
    console.log('obj1不为空');
} else {
    console.log('obj1为空');
}

let obj2 = {a: 1};
if (BASE.isNotNull(obj2) {
    console.log('obj2不为空');
} else {
    console.log('obj2为空');
}

// 判断字符串或数组是否不为空
let obj3 = '';
if (BASE.isNotEmpty(obj3) {
    console.log('obj3不为空');
} else {
    console.log('obj3为空');
}

let obj4 = [{a: 1}];
if (BASE.isNotEmpty(obj4) {
    console.log('obj4不为空');
} else {
    console.log('obj4为空');
}



// 对象转url的query
let url = "http://www.baidu.com";
let query = BASE.objectToUrlQuery({a: 1, b: 2});
let req_url = url + '?' + query;
BASE.LOG.debug(()=>{
    console.log('req_url=', req_url);
});

let query1 = BASE.objectToUrlQuery({a: 1, b: 2, c: {c1: 'c1', c2: '百度'}});
let req_url1 = url + '?' + query1;
BASE.LOG.debug(()=>{
    console.log('req_url1=', req_url1);
});

let query2 = BASE.objectToUrlQuery({a: 1, b: 2, c: {c1: 'c1', c2: '百度'}}, true);
let req_url2 = url + '?' + query2;
BASE.LOG.debug(()=>{
    console.log('req_url2=', req_url2);
});



// 测试TIME
let time = new BASE.TIME();
time.start();
console.log('time=', time);
setTimeout(()=>{
    let time1 = new BASE.TIME();
    time1.start();
    console.log('time1=', time1);
    
    setTimeout(()=>{
        console.log('time1.stop pass_time=', time1.stop().pass_time + '毫秒');
        
        setTimeout(()=>{
            console.log('time.stop pass_time=', time.stop().pass_time + '毫秒');
        }, 2 * 1000);
    }, 5 * 1000);
}, 2 * 1000);

let ps = BASE.TIME.dateFormat(new Date());
console.log('ps 当前时间=', ps);


 

注:

本文涉及到的相关工具类的源码,请看阅本人的其他文章:

TIME类:JS耗时统计工具类——TIME

LOG类:JS日志输出控制工具类——LOG

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值