1. 程式人生 > 其它 >JavaScript 常用工具函式

JavaScript 常用工具函式

1、格式化時間

function dateFormater(formater, t){
    let date = t ? new Date(t) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g,Y)
        .replace(
/YY|yy/g,Y.substr(2,2)) .replace(/MM/g,(M<10?'0':'') + M) .replace(/DD/g,(D<10?'0':'') + D) .replace(/HH|hh/g,(H<10?'0':'') + H) .replace(/mm/g,(m<10?'0':'') + m) .replace(/ss/g,(s<10?'0':'') + s) } // dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30 // dateFormater('YYYYMMDDHHmm', t) ==> 201906261830

2、將指定字串由一種時間格式轉化為另一種。From的格式應對應str的位置

function dateStrForma(str, from, to){
    //'20190626' 'YYYYMMDD' 'YYYY年MM月DD日'
    str += ''
    let Y = ''
    if(~(Y = from.indexOf('YYYY'))){
        Y = str.substr(Y, 4)
        to = to.replace(/YYYY|yyyy/g,Y)
    }else if(~(Y = from.indexOf('YY'))){
        Y 
= str.substr(Y, 2) to = to.replace(/YY|yy/g,Y) } let k,i ['M','D','H','h','m','s'].forEach(s =>{ i = from.indexOf(s+s) k = ~i ? str.substr(i, 2) : '' to = to.replace(s+s, k) }) return to } // dateStrForma('20190626', 'YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日 // dateStrForma('121220190626', '----YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日 // dateStrForma('2019年06月26日', 'YYYY年MM月DD日', 'YYYYMMDD') ==> 20190626 // 也可以使用正則來實現 //'2019年06月26日'.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3') ==> 2019-06-26

3、獲取Url引數,返回一個物件

function GetUrlParam(){
    let url = document.location.toString();
    let arrObj = url.split("?");
    let params = Object.create(null)
    if (arrObj.length > 1){
        arrObj = arrObj[1].split("&");
        arrObj.forEach(item=>{
            item = item.split("=");
            params[item[0]] = item[1]
        })
    }
    return params;
}
// ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}

4、base64資料匯出檔案,檔案下載

function downloadFile(filename, data) {
    let DownloadLink = document.createElement('a');
    if (DownloadLink) {
        document.body.appendChild(DownloadLink);
        DownloadLink.style = 'display: none';
        DownloadLink.download = filename;
        DownloadLink.href = data;
        if (document.createEvent) {
            let DownloadEvt = document.createEvent('MouseEvents');
            DownloadEvt.initEvent('click', true, false);
            DownloadLink.dispatchEvent(DownloadEvt);
        } else if (document.createEventObject) {
            DownloadLink.fireEvent('onclick');
        } else if (typeof DownloadLink.onclick == 'function') {
            DownloadLink.onclick();
        }
        document.body.removeChild(DownloadLink);
    }
}

5、檢查資料是否是非數字值

function _isNaN(v){
    return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)
}

6、求取陣列中非NaN資料中的最大值

function max(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11

7、求取陣列中非NaN資料中的最小值

function min(arr){
    arr = arr.filter(item => !_isNaN(item))
    return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1

8、禁止某些鍵盤事件

document.addEventListener('keydown', function(event) {
    return !(
        112 == event.keyCode ||        //禁止F1
        123 == event.keyCode ||        //禁止F12
        event.ctrlKey && 82 == event.keyCode ||        //禁止ctrl+R
        event.ctrlKey && 18 == event.keyCode ||        //禁止ctrl+N
        event.shiftKey && 121 == event.keyCode ||          //禁止shift+F10
        event.altKey && 115 == event.keyCode ||        //禁止alt+F4
        "A" == event.srcElement.tagName && event.shiftKey        //禁止shift+點選a標籤
    ) || (event.returnValue = false)
});

9、禁止右鍵、選擇、複製

['contextmenu', 'selectstart', 'copy'].forEach(function(ev) {
    document.addEventListener(ev, function(event) {
        return event.returnValue = false;
    })
});

10、數字相除

function numDiv(num1, num2) {
    let baseNum1 = 0, baseNum2 = 0;
    let baseNum3, baseNum4;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    with (Math) {
        baseNum3 = Number(num1.toString().replace(".", ""));
        baseNum4 = Number(num2.toString().replace(".", ""));
        return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1);
    }
};

11、數字相乘

function numMulti(num1, num2) {
    let baseNum = 0;
    try {
        baseNum += num1.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        baseNum += num2.toString().split(".")[1].length;
    } catch (e) {
    }
    return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
};

12、數字相減

function numSub(num1, num2) {
    let baseNum, baseNum1, baseNum2;
    let precision;// 精度
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};

13、數字相加

function numAdd(num1, num2) {
    let baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
};

14、陣列去重,返回一個新陣列

function unique(arr){
    if(!isArrayLink(arr)){ //不是類陣列物件
        return arr
    }
    let result = []
    let objarr = []
    let obj = Object.create(null)
    
    arr.forEach(item => {
        if(isStatic(item)){//是除了symbol外的原始資料
            let key = item + '_' + getRawType(item);
            if(!obj[key]){
                obj[key] = true
                result.push(item)
            }
        }else{//引用型別及symbol
            if(!objarr.includes(item)){
                objarr.push(item)
                result.push(item)
            }
        }
    })
    
    return resulte
}

from思否社群小蘑菇大大的總結,傳送門已附上https://segmentfault.com/a/1190000040224248

認真做事兒,踏實做人