整理了一些简单实用的js公用方法

231 阅读3分钟
//随机获取true/false
export function randomBoolean() {
    return Math.random() >= 0.5
}


//检查日期是否为工作日
export function isWeek(date) {
    return date.getDay()%6 !== 0
    //true为工作日   false为周末
}


//反转字符串
export function reverse(str) {
    return str.split('').reverse().join('')
}


//判断是否为偶数
export function isEven(num) {
    return num % 2 === 0
}


//从日期中获取时间
export function timeFromDate(date) {
    return date.toTimeString().slice(0, 8)
}


//保留小数点(非四舍五入)
export function toFixed(n, fixed) {
    //n代表要处理的数字  fixed代表保留多少位
    return ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed)
}


//检查浏览器是否支持触摸事件
export function touchSupported() {
    return ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch)
}


//检查当前用户是否为苹果设备
export function isAppleDevice() {
    return /Mac|iPod|iPhone|iPad/.test(navigator.platform)
}


//滚动到页面顶部
export function goToTop() {
    window.scrollTo(0, 0)
}


//获取所有参数平均值
export function average(...args) {
    return args.reduce((a, b) => a + b) / args.length
}


//转换华氏度/摄氏度
export function celsiusToFahrenheit(celsius) {
    return celsius * 9/5 + 32
}

export function fahrenheitToCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5/9
}


//金额分转元,保留两位小数
export function moneyFormatter(money){
    if(!money){
        return ''
    }else{
        let val = parseFloat(money) || 0
        let newVal = parseFloat(val/100)
        let forMateVal = newVal.toFixed(2)
        return forMateVal
    }
}


//获取当前时间
export function getDate(){
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    let nowDate = year + "-" + month + "-" + day;
    return nowDate
}


//获取月份第一天 , 如果为当前为1号,则获取上一月的第一天
export function getMonthDayFirst() {
    let nowdays = new Date();
    let year = nowdays.getFullYear();
    let month = nowdays.getMonth();  //上个月
    let day = nowdays.getDate()
    //当前不是一号  则直接返回当前月的第一天
    if (day != 1) {
        return getCurrentMonthFirst()
    }
    //当前日期是一号  则返回上一个月的第一天
    if (month == 0) {
        month = 12;
        year = year - 1;
    }
    if (month < 10) {
        month = '0' + month;
    }
    let myDate = new Date(year, month, 0);
    let startDate = year + '-' + month + '-01'; //上个月第一天
    return startDate
}


//导出数据
export function exportDateHand(blobVal, fileName = '数据导出') {
    let blob = blobVal;
    let reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = e => {
        let a = document.createElement("a");
        a.download = fileName;
        a.href = e.target.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    };
}


// 随机生成颜色
export function createColorCode() {
    return '#' + Math.floor(Math.random() * 16777215).toString(16);
}


//获取设备系统类型
export function getDeviceOSType() {
    let _return = "pc";

    let ua = navigator.userAgent.toLowerCase();
    if (/iphone|ipad|ipod/.test(ua)) {
        _return = "ios"
    }
    else if (/android/.test(ua)) {
        _return = "android"
    }

    return _return;
}


//阻止事件冒泡
export function stopEventPropagation() {
    if (event.stopPropagation) {
        event.stopPropagation();
    }
    else if (window.event) {
        //IE浏览器
        window.event.cancelBubble = true;
    }
}


//js克隆
export function clone(obj) {
    let newObj;
    switch (typeof obj) {
        case 'undefined':
            break;
        case 'string':
            newObj = obj + '';
            break;
        case 'number':
            newObj = obj - 0;
            break;
        case 'boolean':
            newObj = obj;
            break;
        case 'object':
            if (obj === null) {
                newObj = null;
            }
            else {
                newObj = JSON.parse(JSON.stringify(obj));
            }
            break;
        default:
            newObj = obj;
            break;
    }
    return newObj;
}


//字符串转utf-8编码
export function strToUtf8(text) {
    var out, i, len, c;
    out = "";
    len = text.length;
    for (i = 0; i < len; i++) {
        c = text.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += text.charAt(i);
        }
        else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
        else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}


//去空格
export function toTrim(x) {
    return x.replace(/^\s+|\s+$/gm,'');
}


//设置cookie
export function setCookie(name, value, iDay) {
    //name: cookie名称     value:cookie值    iDay:cookie的时间
    let oDate = new Date();
    oDate.setDate(oDate.getDate() + iDay);
    document.cookie = name + '=' + value + ';expires=' + oDate;
}


//获取cookie
export function getCookie(name) {
    //name :cookie名称
    let arr = document.cookie.split('; ');
    for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split('=');
        if (arr2[0] == name) {
            return arr2[1];
        }
    }
    return '';
}


//删除cookie
export function removeCookie(name) {
    setCookie(name, 1, -1);
}


//数组去重
export function removeRepeatArray(arr) {
    return Array.from(new Set(arr))
}


//将数组乱序输出
export function upsetArr(arr) {
    return arr.sort(function() { return Math.random() - 0.5 })
}


//获取数组的最大值,最小值,只针对数字类型的数组
export function compareArr(arr,type) {
    //type 0:最大值  1:最小值
    if (type === 1) {
        return Math.max.apply(null, arr);
    } else {
        return Math.min.apply(null, arr);
    }
}


//倒计时
export function getEndTime(endTime) {
    let startDate = new Date(); //开始时间,当前时间
    let endDate = new Date(endTime); //结束时间,需传入时间参数
    let t = endDate.getTime() - startDate.getTime(); //时间差的毫秒数
    let d = 0,
        h = 0,
        m = 0,
        s = 0;
    if (t >= 0) {
        d = Math.floor(t / 1000 / 3600 / 24);
        h = Math.floor(t / 1000 / 60 / 60 % 24);
        m = Math.floor(t / 1000 / 60 % 60);
        s = Math.floor(t / 1000 % 60);
    }
    return "剩余时间" + d + "天 " + h + "小时 " + m + " 分钟" + s + " 秒";
}


//-------------------加解密逻辑--------------------

//使用时需要下载CryptoJS
//获取uuid
export function getUUID() {
    return 'xxxxxxxxxxxx4xyx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
    })
}

function Encrypt(word, rand) {
    var key = CryptoJS.enc.Utf8.parse(rand);
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}
//解密
function Decrypt(word, rand) {
    var key = CryptoJS.enc.Utf8.parse(rand);
    var decrypt = CryptoJS.AES.decrypt(word, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
/**getEncryptData  getDecryptData 配套使用
 * 加解密key(uuid) 私钥值,要和后端的key相同 传送给后端
 * 加密
 * @param {Object} params
 * @param {String} rand    uuid
 * @returns {Object}
 */
export function getEncryptData(params, rand, type = 'Object') {
    var paramStr = ''
    if (type == 'Object') {
        paramStr = JSON.stringify(params)
    } else {
        paramStr = params
    }
    var data = Encrypt(paramStr, rand);
    // rsa加密  //使用公钥加密 key
    var encrypt = new JSEncrypt();
    var publickKey = store.state.user.publicKey
    encrypt.setPublicKey(publickKey);
    var encrypted = encrypt.encrypt(rand);
    // 创建json对象
    var json = {
        "requestData": data,
        "encrypted": encrypted
    };
    return json
}
/**
 * getEncryptData  getDecryptData 配套使用
 * 解密
 * @param {String} word
 * @param {String} rand    加密时的uuid
 * @returns {String}
 */
export function getDecryptData(word, rand, type = 'Object') {
    var decData = ''
    try {
        decData = Decrypt(word, rand)
    } catch (e) { }

    if (decData && type == 'Object') {
        return JSON.parse(decData)
    } else {
        return decData
    }

}

/**
 * 仅解密,单独使用 (仅后端加密,前端解密)
 * @param {String} word
 * @param {String} rand    加密时的uuid
 * @returns {String}
 */
export function getSimpDecryptData(word, type = 'Object') {
    var rand = store.state.user.simpDecryptKey
    var decData = ''
    try {
        decData = Decrypt(word, rand)
    } catch (e) { }
    if (decData && type == 'Object') {
        return JSON.parse(decData)
    } else {
        return decData
    }

}

//-----------------------------------------------------------------