前端通用函数

179 阅读2分钟

节流函数

--规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

function throttle(fun, delay) {
    let last, deferTimer
    return function (args) {
        let that = this
        let _args = arguments
        let now = +new Date()
        if (last && now < last + delay) {
            clearTimeout(deferTimer)
            deferTimer = setTimeout(function () {
                last = now
                fun.apply(that, _args)
            }, delay)
        }else {
            last = now
            fun.apply(that,_args)
        }
    }
}

防抖函数

--在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时

 function debounce(fun, delay) {
    return function (args) {
        let that = this
        clearTimeout(fun.id)
        fun.id = setTimeout(function () {
            fun.call(that, args)
        }, delay)
    }
}

升序/降序

var arr = [5,44,8,20];
// 升序
console.log(arr.sort(function (a, b) {
    return a - b;
}));    //  [5, 8, 20, 44]
// 降序
console.log(arr.sort(function (a, b) {
    return b - a;
}));   //  [44, 20, 8, 5]

冒泡排序

 // 冒泡排序
function bubbleSort(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
      for (let j = 0; j < i; j++) {
        if (arr[j] > arr[j + 1]) {
          swap(arr, j, j + 1);
        }
      }
    }
    return arr;
}

// 置换函数
function swap(arr, indexA, indexB) {
    [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]];
}

是否是对象

obj.constructor === Object

是否是数组

function isArray(arr) {
    return Object.prototype.toString.call(arr).slice(8, -1) === 'Array';
}

对象/数组是否存在该key

// 对象内是否存在:  
hasOwnProperty(key)
// 数组内是否存在:  
has(value)

数组去重

function distinct(arr = testArr) {
    return arr.filter((v, i, array) => array.indexOf(v) === i)
}

深克隆

function deepClone(obj) {
    if(typeof obj !== 'object' || typeof obj !== 'function') {
        return obj;
    }
    var o = isArray(obj) ? [] : {};
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            //递归调用
            o[i] = (typeof obj[i] === 'object') ? deepClone(obj[i]) : obj[i];
        }
    }
    return o;
}

生成随机数

function randombetween(min, max) {
    return min + (Math.random() * (max - min + 1));
}

清除字符串前后的空格

 function trim(s){
    return s.replace(/(^\s*)|(\s*$)/g, "");
 }

时间戳转换

//部0
    add0(m) {
      return m < 10 ? '0' + m : m
    },
//时间戳转换
    format(shijianchuo) {
      //shijianchuo是整数,否则要parseInt转换
      let time = new Date(shijianchuo);
      let y = time.getFullYear();
      let m = time.getMonth() + 1;
      let d = time.getDate();
      let h = time.getHours();
      let mm = time.getMinutes();
      let s = time.getSeconds();
      return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s);
    }

设置cookie

function setCookie(name, value) {
    const Days = 30; //一个月
    let exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie =
        name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

获取cookie

function getCookie(name) {
    let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) {
        return arr[2];
    } else {
        return "";
    }
}

删除cookie

function delCookie(name) {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
}

设置sessionStorage 保存后浏览器关闭值即消失

function setSessionStorage(key, value) {
    if (window.sessionStorage) {
        window.sessionStorage.setItem(key, window.JSON.stringify(value));
    }
}

获取sessionStorage

function getSessionStorage(key) {
    var json = "";
    if (window.sessionStorage) {
        json = window.sessionStorage.getItem(key);
    }
    return window.JSON.parse(json);
}

删除sessionStorage

function deleteItem() {
    sessionStorage.removeItem('userinfo');
    console.log(sessionStorage.getItem('userinfo'));
}

设置localStorage 保存后永久有效

function setLocalStorage(key, value) {
    if (window.localStorage) {
        window.localStorage.setItem(key, window.JSON.stringify(value));
    }
}

获取localStorage

function getLocalStorage(key) {
    var json = "";
    if (window.localStorage) {
        json = window.localStorage.getItem(key);
    }
    return window.JSON.parse(json);
}

删除localStorage

function deleteItem() {
    localStorage.removeItem('userinfo');
    console.log(localStorage.getItem('userinfo'));
}