tools工具函數

js 將多維數組轉爲一維數組:

var arr = [1,[2,[[3,4],5],6]];
function unid(arr){
        var arr1 = (arr + '').split(',');
        var arr2 = arr1.map(function(x){
            return Number(x);
        });
        return arr2;
}
console.log(unid(arr));
複製代碼

防抖函數

tools.debounce = function (fn, delay = 300) {
    let handle;
    return function (e) {
        // 取消以前的延時調用
        clearTimeout(handle);
        handle = setTimeout(() => {
            fn(e);
        }, delay);
    }
}
複製代碼

經過toString方法獲取類型

tools.getType = (obj) => {
    var type = '';
    var typeArr = ['String', 'Object', 'Number', 'Array', 'Undefined', 'Function', 'Null', 'Symbol'];
    for (var i = 0; i < typeArr.length; i++) {
        if (Object.prototype.toString.call(obj) == '[object ' + typeArr[i] + ']') {
            type = typeArr[i]
        }
    }
    return type;
}
複製代碼

數據深拷貝

tools.deepCopy = (p, c) => {
    var c = c || {};
    for (var i in p) {
        if (typeof p[i] === 'object') {
            if (p[i] === null) {
                c[i] = null;
            } else {
                c[i] = (p[i].constructor === Array) ? [] : {};
                tools.deepCopy(p[i], c[i]);
            }
        } else {
            c[i] = p[i];
        }
    }
    return c;
}
複製代碼

設置本地存儲和本地讀取

//獲取本地存儲
tools.getStorage = key => {
    const re = /^\[|\{|\}|\]$/g //判斷字符中是否有[]{}
    let getIt = localStorage.getItem(key)
    if (re.test(getIt)) {
        return JSON.parse(getIt)
    } else {
        return getIt
    }
}

//設置本地存儲
tools.setStorage = (key, val) => {
    if (typeof val == 'string') {
        //若是傳過來的是字符串,那麼說明要保存的是id
        localStorage.setItem(key, val)
    } else {
        //若是傳過來的不是字符串,要保存數組
        localStorage.setItem(key, JSON.stringify(val))
    }
}
複製代碼

獲取多維數組的層級

function getArrTier(arr){
    if (!Array.isArray(arr)) throw('type error')
    let strArr = JSON.stringify(arr).split(']'),num = 0
    for(let i = 0; i < strArr.length;i++){
        let str2Arr = strArr[i].split('[')
        if(num < str2Arr.length){
            num = str2Arr.length
        }
    }
    return num
}
複製代碼
相關文章
相關標籤/搜索