总结一些js常用的公共方法

328 阅读1分钟

一、深拷贝

代码

export function deepCopy (p, cq) {
    var c = cq || {};
    for (var i in p) {
        if (p[i] && typeof p[i] == 'object') {
            c[i] = (p[i].constructor === Array) ? [] : {};
            this.deepCopy(p[i], c[i]);
        } else {
            c[i] = p[i];
        }
    }
    return c;
}

使用

deepCopy(array, [])

或

deepCopy(object, {})

二、获取地址参数

方法1:

代码

export function getUrlParams () {
    let params = decodeURIComponent(location.href),
    search = params.split('?')[1],
    obj = {};
    if (!search) {
        return obj;
    }
    // 写入数据字典
    var tmparray = search.substr(0, search.length).split('&');
    if (tmparray != null) {
        for (var i = 0; i < tmparray.length; i++) {
            var reg = /[=|^==]/; // 用=进行拆分,但不包括==
            var set1 = tmparray[i].replace(reg, '&');
            var tmpStr2 = set1.split('&');
            obj[tmpStr2[0]] = tmpStr2[1];
        }
    }
    return obj;
}

使用

let id = getUrlParams().id

方法2:

代码

export const queryString = function(key) {
    var result = new RegExp('[\\?&]' + key + '=([^&#]*)', 'i').exec(window.location.href);
    return result && decodeURIComponent(result[1]) || '';
}

使用

let id = queryString('id');

三、关于本地储存

代码

export function saveToLocalStorage (key, value) {
    if (key == null) {
        return;
    }
    if (value == null) {
        localStorage.removeItem(key);
    } else {
        localStorage.setItem(key, JSON.stringify(value));
    }
}

export function getFromlocalStorage (key) {
    var res = localStorage.getItem(key);
    if (res) {
        return (res + '').indexOf('{') > -1 ? JSON.parse(res) : res;
    } else {
        return null;
    }
}

export function saveToSessionStorage (key, value) {
    if (key == null) {
        return;
    }
    if (value == null) {
    sessionStorage.removeItem(key);
    } else {
    sessionStorage.setItem(key, JSON.stringify(value));
    }
}

export function getFromSessionStorage (key) {
    var res = sessionStorage.getItem(key);
    if (res) {
        return (res + '').indexOf('{') > -1 ? JSON.parse(res) : res;
    } else {
        return null;
    }
}

使用

saveToLocalStorage('searchHistory', [searchHistory])

getFromlocalStorage('searchHistory')

saveToSessionStorage('searchHistory', [searchHistory])

getFromSessionStorage('searchHistory')

四、把时间戳转成时间

代码

export function timestampToTime (timestamp) {
    if (timestamp && typeof(timestamp) == 'number'){
        let newTime = timestamp.length == 13 ? timestamp : timestamp * 1000;
        let date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        // h = date.getHours() + ':';
        // m = date.getMinutes() + ':';
        // s = date.getSeconds();
        return Y + M + D;
    }
}

使用

timestampToTime(timeStart)

五、下载文件

代码

export function downloadFile (url, fileName) {
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true; //允许跨域携带cookie
    xhr.open('GET', url, true);
    xhr.responseType = 'blob'; // 返回类型blob
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob); // 转换为base64,可以直接放入a-href
            reader.onload = function (e) {
                // 转换完成,创建一个a标签用于下载
                var a = document.createElement('a');
                a.download = fileName;
                a.href = URL.createObjectURL(base64ToBlob(e.target.result)); //解决下载base64地址大于2m的情况
                a.target = '__blank';
                document.body.appendChild(a);
                a.click();
                a.remove();
            };
        }
    };
    xhr.send();
}

使用

downloadFile( downloadFile,`内容导入模板.xls`)