工作上常用方法(持续更新)

98 阅读3分钟

日期

日期转'YYYY-MM-DD'等格式

/**
* 用法 dateFormat('yy-MM-dd HH:mm:ss');
* @param {type} fmt
* @returns {unresolved}
*/

dateFormat (date, fmt) {
    // 默认值
    if (fmt == null) {
        fmt = 'yyyy-MM-dd HH:mm:ss'
    }
    var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
        'H+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
    }

    var week = {
        '0': '/u65e5',
        '1': '/u4e00',
        '2': '/u4e8c',
        '3': '/u4e09',
        '4': '/u56db',
        '5': '/u4e94',
        '6': '/u516d'
    }

    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }

    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + week[date.getDay() + ''])
    }
    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
},

根据字符串返回Date 类型

/**
    * [parse 根据字符串返回Date 类型]
    * yyyy--MM--dd HH:mm:ss
    * 2012--01--12 14:14:59
*/

dateParse : function (fmt, str) {
    var map = {
        year: "y",
        day: "d",
        month: "M",
        hour: "H",
        minute: "m",
        second: "s"
    };
    // 获取值
    var getMapValure = function (type) {
        var start = fmt.indexOf(type);
        if(start == -1) {
            return 0;
        }
        var end = fmt.lastIndexOf(type);
        return str.substring(start, end + 1);
    };
    var year = getMapValure(map.year);
    var month = getMapValure(map.month);
    var day = getMapValure(map.day);
    var hour = getMapValure(map.hour);
    var minute = getMapValure(map.minute);
    var second = getMapValure(map.second);
    return new Date(year, month - 1, day, hour, minute, second);
},

数组

深层优先遍历

    // 深层优先遍历
    treeIterator(tree, func) {
      tree.forEach((node) => {
        func(node)
        node.children && this.treeIterator(node.children, func)
      })
    },
    // 使用示例改变某个list中的checked值
    // 遍历全部的对象 设置checked
    this.treeIterator(list,(node)=>{
      if(val.includes(node.id)){
        node.checked = true
      }
    })
    

字符串

去除多余空格

 // 去除多余空格
    clearBlank(val){
        return val.replace(/\s*/g,"")
    },

截取前几个字,并用...代替

    // 截取前几个字

    ellipsis:function(value, len) {
        if (!value) return ''
        if (value.length > len) {
            return value.slice(0, len) + '...'
        }
        return value
    },

去掉两边的空白


// 除去两边空白

trim : function(str) {
    if(this.isString(str)) {
        return str.replace(/(^\s+)|(\s+$)/g, "");
    } else {
        return str;
    }
},

去除多余空格

clearBlank(val){
    return val.replace(/\s*/g,"")
},

数字

四舍五入

round(number, precision) {

    if (isNaN(number)) {
        number = 0
    }
    if (number > 0) {
        return (parseInt(number * Math.pow(10, precision) + 0.5) / Math.pow(10, precision))
    } else if (number < 0) {
        return (parseInt(number * Math.pow(10, precision) - 0.5) / Math.pow(10, precision))
    } else {
        return (parseInt(number * Math.pow(10, precision)) / Math.pow(10, precision))
    }
}

截取N位小数(直接截取,不进行四舍五入)

fixed(number, precision) {
    if (isNaN(number) || number === '' || number == null) {
        number = 0
    }
    let result = number.toString()
    if (result.indexOf('.') === -1) {
        result = result + '.'
    }
    let tempStr = ''
    for (let i = 0; i < precision; i++) {
        tempStr = tempStr + '0'
    }
    result = result + tempStr
    result = result.substring(0, precision + result.indexOf('.') + 1)
    if (result.endsWith('.')) {
        result = result.substring(0, result.length - 1)
    }
    return result
}

取整

/**
    * 取整
    * @param {[type]} number [保费]
    * @param {[type]} flag [标志。-1表示向下取整;0表示四舍五入;1或者不含这参数表示向上取整]
    * @return {[type]} [description]
*/

adjustValue(number, flag) {
    let OldValue = parseFloat(number)
    let NewValue = 0
    if (flag === -1) {
        NewValue = Math.floor(OldValue)
    } else if (flag === 0) {
        NewValue = Math.round(OldValue)
    } else if (flag === undefined || flag === 1) {
        NewValue = Math.ceil(OldValue)
    }
    return NewValue
}

校验验证

校验输入数字是否是整数

/**
    * 校验输入数字是否是整数
    * @param {[type]} strValue [description]
    * @return {[type]} [description]
*/

isInteger(strValue) {
    if (strValue) {
        let reg = /\d+/g
        if (strValue == reg.exec(strValue)) {
            return true
        }
    }
    return false
}

校验密码(大小写,数字,特殊字符)

passwordValid(str){  
    // 写出数字、大小写字母、字符这4种正则表达式  
    const rC = {  
        lw'[a-z]',  
        uw'[A-Z]',  
        nw'[0-9]',  
        // rw: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'  
        sw'[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'  
    }  
    // 写出正则校验函数  
    function Reg(str,rStr){  
        const reg = new RegExp(rStr);  
        if(reg.test(str)){  
        return true;  
        } else {  
        return false;  
        }  
    }  
    // 封装  
    const tR = {  
        lReg(str, rC.lw),  
        uReg(str, rC.uw),  
        nReg(str, rC.nw),  
        sReg(str, rC.sw)  
    }  
    // 校验  (大写+小写+数字 或者 大写+小写+特殊字符)
    if(str && str.length < 10){  
        return false;  
    } else {  
        if((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s)){  
        return true;  
        }else{  
        return false;  
        }  
    }  
}

其他工具方法

JS生成uuid方法

    getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        var uuid = s.join("");
        return uuid;
    },

JS生成uuid,并且去掉字符串中的 '-'

    getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
    
        var uuid = s.join("");

        uuid = uuid.replace(/[-]/g,"");
        return uuid;
    },s[18] = s[23] = "-";
    
        uuid = uuid.replace(/[-]/g,"");
        var uuid = s.join("");
        return uuid;
    },

file文件转换成base64编码

fileByBase64(file, callback){
    var reader = new FileReader();
    // 传入一个参数对象即可得到基于该参数对象的文本内容
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        // target.result 该属性表示目标对象的DataURL
        console.log(e.target.result);
        callback(e.target.result)
    };
},

判断是否为IE浏览器

isIE: function() {
    if(!!window.ActiveXObject || "ActiveXObject" in window){
        return true;
    }else{
        return false;
    }
},

简单深拷贝

function deepClone(obj){
    var newObj= obj instanceof Array ? []:{};
    for(var item in obj){
        var temple= typeof obj[item] == 'object' ? deepClone(obj[item]):obj[item];
        newObj[item] = temple;
    }
    return newObj;
}