项目中封装一些实用方法

 获取url参数。 

举例:https://csdn.net/index?name=xiaomin

getQueryString('name').               //. xiaoming

/**
 * 获取url参数
 * @param {String} name
 * @param {*}
 */
export const getQueryString = (name) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, "i");
    const r = window.location.search.substr(1).match(reg);
    if (r != null) { return decodeURIComponent(r[2]); }
    return '';
};

 时间戳转时间

   1552997048 <<------- >>     2019/03/19 20:04:08

// 时间戳转时间
export const  getLocalTime = (nS) => {
    if (nS === '0' && !nS) {
        return '--------';
    }
    nS = nS.length === 13 ? nS : nS * 1000;
    let toDouble = (m) => {
        return m < 10 ? '0' + m : m;
    };
    let time = new Date(nS);
    if (!time) {
        return null;
    }
    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}/${toDouble(m)}/${toDouble(d)}  ${toDouble(h)}:${toDouble(mm)}:${toDouble(s)}`;
};

 保留两位小数

export const fomatFloat = (num, n = 2) => {
    let f = parseFloat(num);
    if (isNaN(f) || num === 0) {
        return '';
    }
    f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 幂
    var s = f.toString();
    var rs = s.indexOf('.');
    // 判定如果是整数,增加小数点再补0
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + n) {
        s += '0';
    }
    return s;
};

 数组去重

export const noRepeat = (arr) => {
    arr = arr || [];
    let newArr = [];
    arr.forEach(
        item => {
            if (!newArr.find(val => val.id === item.id
                && val.deliveryType === item.deliveryType)) {
                newArr.push(item);
            }
        }
    );
    return newArr;
};

防抖debounce代码: 

export const debounce = (fn, delay) => {
    let timeout = null; // 创建一个标记用来存放定时器的返回值
    return function () {
        // 每当用户输入的时候把前一个 setTimeout clear 掉
        clearTimeout(timeout);
        // 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
            timeout = null;
        }, delay);
    };
};

 生成随机id

export const getId = (length = 8) => {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
};

你可能感兴趣的:(javascript,前端,开发语言)