commons.js 2.19 KB
/**
 * @file commons
 * Created by He 2020/07/22
 * @brief 通用方法
 * @author liuyuan
 */
export default {
    /**
     * @brief 依次打印出来, 正式版本要去的掉
     * @param  {...any} args (1,2,3)
     */
    log(...args) {
        args.forEach(val => {
            console.log(val);
        });

    },
    /**
     * @param {*} fmt  '2020-07-22'
     * @param {*} date  new Date()
     */
    dateZhuan(fmt, date) {
        //日期格式转换
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },
    /**
     * @brief 纯数组去重
     * @param {*} arr [1, 1, 33, 33, 2]
     */
    unique: function (arr) {
        var newArr = [];
        var len = arr.length
        for (var i = 0; i < len; i++) {
            if (arr.indexOf(arr[i]) == i) {
                newArr.push(arr[i]);
            }
        }
        return newArr;
    },
    /**
     * @brief:深度拷贝
     * @param {*} data => obj
     * */
    deepClone: function (data) {
        var type = this.getType(data);
        var obj;
        if (type === 'array') {
            obj = [];
        } else if (type === 'object') {
            obj = {};
        } else {
            //不再具有下一层次
            return data;
        }
        if (type === 'array') {
            for (var i = 0, len = data.length; i < len; i++) {
                obj.push(this.deepClone(data[i]));
            }
        } else if (type === 'object') {
            for (var key in data) {
                obj[key] = this.deepClone(data[key]);
            }
        }
        return obj;
    },
}