全速加载中...
登录
首页
文章
随笔
留言
友链
订阅
关于
更多
湘ICP备2021007748号-4
湘公网安备案湘公网安备43052202000137号
又拍云

常用方法封装:防抖节流,判断手机号等

这只是几个函数的封装,单独拿出来即可使用。部分方法可参考文档:点击前往

一,数组

  • 获取数组对象中某个属性的值组成新的数组
  • 获取数组中指定值的重复数量
  • 清除数组中指定的值
  • 数组扁平化
javascript 复制代码
/**
 * @function
 * 获取数组对象中某个属性的值组成新的数组。
 * @param
 * arrObj:数组对象
 * prop: 属性名
 */
export const  getArrObjProp = (arrObj, prop) => {
    return arrObj.map(item => item[prop]).filter(val => val !== undefined)
};


/**
 * @function
 * 获取数组中指定值的重复数量。
 * @param
 * arr:数组
 * val: 指定的值
 */
export const  countOccurrences=(arr, val) => {
    return arr.reduce((acc, cur) => (cur === val ? acc + 1 : acc), 0);
}

/**
 * @function
 * 清除数组中指定的值。
 * @param
 * arr:数组
 * values: 数组:指定的值
 */
export const  cleanArray=(arr, values=[])=> {
    return arr.filter(item => !values.includes(item));
}
/**
 * @function
 * 数组扁平化
 * @param
 * arr:数组
 */
export const flatten=(arr) =>{
    return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}


export const  z_array={
    cleanArray,
    countOccurrences,
    getArrObjProp,
    flatten,
}

二,Cookie

  • 设置cookie
  • 修改cookie,没有则新增。
  • 获取cookie,没有则返回null。
  • 删除cookie
JavaScript 复制代码
/**
 * @function
 * 设置cookie。
 * @param
 * name:键名
 * value:值
 * days:天数
 */
const  setCookie=(name, value, days) =>{
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

/**
 * @function
 * 修改cookie,没有则新增。
 * @param
 * name:键名
 * value:值
 * days:天数
 */
const  updateCookie=(name, value, days) =>{
    setCookie(name, value, days);
}

/**
 * @function
 * 获取cookie,没有则返回null。
 * @param
 * name:键名
 * value:值
 * days:天数
 */
const getCookie=(name)=> {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

/**
 * @function
 * 删除cookie。
 * @param
 * name:键名
 */
const  deleteCookie=(name) =>{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()+";path=/";
}
export const  z_cookie={
    setCookie,
    deleteCookie,
    updateCookie,
    getCookie,
}

三,日期

  • 判断是否是时间戳
  • 获取当前时间搓
  • 判断日期距离某个日期过去多少时间
  • 计算两个日期相差的时间
  • 格式化时间
  • 获取星期几
JavaScript 复制代码
/***
 * @function
 * 判断是否是时间戳
 */
 const isTimestamp=(str)=>{
  return /^\d{10}$/.test(str) || /^\d{13}$/.test(str);
}
/***
 *
 * @function
 * 获取当前时间搓。
 * @param
 * dateString:时间字符串。
 * format:日期格式
 */
const timestamp = (dateString,format='YYYY-MM-DD hh:mm:ss') => {
  if(isTimestamp(dateString)){
    return   formatTime(new Date(parseInt(dateString)),format)
  }else{
    return dateString? new Date(dateString).getTime() : new Date().getTime()

  }

}
/***
 *
 * @function
 * 判断日期距离某个日期过去多少时间。
 * @param
 * date:日期字符串。
 * nowDate:默认当前日期
 */
 const getTimeDiff=(dateStr,nowDate=new Date())=> {
  const diff = new Date(nowDate) - new Date(dateStr);
  const msPerMinute = 60 * 1000;
  const msPerHour = msPerMinute * 60;
  const msPerDay = msPerHour * 24;
  const msPerMonth = msPerDay * 30;
  const msPerYear = msPerDay * 365;
  let result;
  if (diff < msPerMinute) {
    result = Math.round(diff / 1000) + '秒前';
  } else if (diff < msPerHour) {
    result = Math.round(diff / msPerMinute) + '分钟前';
  } else if (diff < msPerDay) {
    result = Math.round(diff / msPerHour) + '小时前';
  } else if (diff < msPerMonth) {
    const days = Math.round(diff / msPerDay);
    result = days <= 30 ? days + '天前' : formatTime(new Date(dateStr));
  } else if (diff < msPerYear) {
    result = Math.round(diff / msPerMonth) + ' 个月前';
  } else {
    result = Math.round(diff / msPerYear) + ' 年前';
  }
  return result;
}
/***
 *
 * @function
 * 计算两个日期相差的时间。
 * @param
 * date1:日期1。
 * date2:日期2。
 * diffType:类型:year,month,day,hour,minute,second
 */
 const  dateDiff=(date1, date2, diffType='day')=> {
  var diff = new Date(date1).getTime() -  new Date(date2).getTime();
  var diffMap = {
    year: 31536000000,
    month: 2592000000,
    day: 86400000,
    hour: 3600000,
    minute: 60000,
    second: 1000
  };
  return Math.floor(diff / diffMap[diffType]);
}

/***
 *
 * @function
 * 格式化时间。
 * @param
 * date:日期。
 * format:格式,默认:YYYY-MM-DD hh:mm:ss
 */
const  formatTime=(date, format='YYYY-MM-DD hh:mm:ss') =>{
  date=new Date(date);
  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1);
  const day = padZero(date.getDate());
  const hour = padZero(date.getHours());
  const minute = padZero(date.getMinutes());
  const second = padZero(date.getSeconds());
  return format.replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('hh', hour)
      .replace('mm', minute)
      .replace('ss', second);
}
function padZero(num) {
  return num < 10 ? '0' + num : num;
}
/***
 *
 * @function
 * 获取星期几。
 * @param
 * date:日期,默认当前日期。
 *
 */
 const  getWeekday=(date=new Date())=> {
  const weekdays =["日", "一", "二", "三", "四", "五", "六"];
  return '星期'+weekdays[new Date(date).getDay()];
}

export const  z_date={
  getWeekday,
  isTimestamp,
  timestamp,
  getTimeDiff,
  dateDiff,
  formatTime
}

四,其他方法

  • 防抖
  • 节流
  • 获取随机数
  • 判断是否数组
  • 判断是否对象
  • 判断是否函数
  • 判断是否String
  • 判断是否为空
  • 判断是否为中文
  • 判断是否为手机号
  • 判断是否为邮箱
  • 随机生成指定长度的字符串
  • 获取客户端信息
  • 删除字符串中指定字符
JavaScript 复制代码
/**
 * @function
 * 防抖。
 * @param
 * func:方法
 * delay:延迟时间默认:500
 */
const   debounce=(func, delay=500) =>{
    let timer = null;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    }
}
/**
 * @function
 * 节流。
 * @param
 * func:方法
 * delay:延迟时间默认:500
 */
const   throttle=(func, delay=500) =>{
    let timer = null;
    return function() {
        if (!timer) {
            timer = setTimeout(() => {
                func.apply(this, arguments);
                timer = null;
            }, delay);
        }
    };
}




/**
 * @function
 * 获取随机数。
 * @param
 * min:最小值
 * max:最大值
 */
const   randomNumber=(min=0, max=100)=> {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


/**
 * @function
 * 判断是否数组。
 * @param
 * obj:判断的值
 */
const   isArray=(obj) =>{
    return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
 * @function
 * 判断是否对象。
 * @param
 * obj:判断的值
 */
const  isObject=(obj)=> {
    return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
 * @function
 * 判断是否函数。
 * @param
 * obj:判断的值
 */
const isFunction=(obj)=> {
    return Object.prototype.toString.call(obj) === '[object Function]';
}/**
 * @function
 * 判断是否String。
 * @param
 * obj:判断的值
 */
const isString=(obj)=> {
    return typeof obj === 'string';
}
/**
 * @function
 * 判断是否为空。
 * @param
 * obj:判断的值
 */
 const isEmpty=(obj) =>{
    if (obj === null || obj === undefined) {
        return true;
    }
    if (isArray(obj) || isString(obj)) {
        return obj.length === 0;
    }
    if (isObject(obj)) {
        return Object.keys(obj).length === 0;
    }
    return false;
}
/**
 * @function
 * 判断是否为中文。
 * @param
 * obj:判断的值
 */
const isChinese=(obj) =>{
    var reg = /^[\u4e00-\u9fa5]+$/;
    return reg.test(obj);
}
/**
 * @function
 * 判断是否为手机号。
 * @param
 * obj:判断的值
 */
const isPhoneNumber=(obj) =>{
    const regExp = /^1[3456789]\d{9}$/;
    return regExp.test(obj);
}/**
 * @function
 * 判断是否为邮箱。
 * @param
 * obj:判断的值
 */
const isEmail=(str)=> {
    var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return reg.test(str);
}

/**
 * @function
 * 随机生成指定长度的字符串。
 * @param
 * length:长度(默认6)
 */
 const generateRandomString=(length=6)=> {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}


/**
 * @function
 * 获取客户端信息。
 * @param
 * userAgent:用户设备信息,
 * language:语言,
 * isMobile:是否手机端
 * isTablet:是否平板电脑
 * isDesktop:是否台式机
 */
const getClientInfo=() =>{
    const userAgent = navigator.userAgent;
    const language = navigator.language;
    const isMobile = /Mobile/i.test(userAgent);
    const isTablet = /Tablet/i.test(userAgent);
    const isDesktop = !isMobile && !isTablet;
    return {
        userAgent,
        language,
        isMobile,
        isTablet,
        isDesktop,
    };
}

/**
 * @function
 * 删除字符串中指定字符。
 * @param
 *  str:字符串。
 *  chars:要删除的值,数组
 */
const removeChars=(str, chars=[])=> {
    const regex = new RegExp(chars.join('|'), 'g');
    return str.replace(regex, '');
}

export const  z_func={
    randomNumber,
    throttle,
    debounce,
    isArray,
    isObject,
    isFunction,
    isEmpty,
    isString,
    isChinese,
    isPhoneNumber,
    isEmail,
    generateRandomString,
    getClientInfo,
    removeChars,
}
【版权声明】
✨ 本文来自 [张苹果博客] ✨
🌿 你可以:自由转发到社交网络或个人网站。
🌿 你需要:标注作者并附上本文链接(就像给文章留个回家地址~)。
上一篇 下一篇

评论一下

评论列表

 
暂无评论
ZhangApple
发布日期:2024年02月28日