js实用工具代码(纯代码)

js实用工具代码(纯代码)

💨防抖/节流

📌简单介绍

  • 防抖:指定时间内 频繁触发一个事件,以最后一次触发为准
  • 节流:指定时间内 频繁触发一个事件,只会触发一次

应用场景有很多比如:
防抖是: input搜索,用户在不断输入内容的时候,用防抖来减少请求的次数并且节约请求资源

节流:场景普遍就是按钮点击,一秒点击 10 下会发起 10 次请求,节流以后 1 秒点再多次,都只会触发一次

    // 防抖
    // fn 需要防抖的函数,delay 为定时器时间
    function debounce(fn,delay){
        let timer =  null  // 用于保存定时器
        return function () { 
            // 如果timer存在 就清除定时器,重新计时
            if(timer){
                clearTimeout(timeout);
            }
            //设置定时器,规定时间后执行真实要执行的函数
            timeout = setTimeout(() => {
               fn.apply(this);
            }, delay);
        }
    }
    
    // 节流
    function throttle(fn) {
      let timer = null; // 首先设定一个变量,没有执行定时器时,默认为 null
      return function () {
        if (timer) return; // 当定时器没有执行的时候timer永远是false,后面无需执行
        timer = setTimeout(() => {
          fn.apply(this, arguments);
           // 最后在setTimeout执行完毕后再把标记设置为true(关键)
           // 表示可以执行下一次循环了。
          timer = null;
        }, 1000);
      };
    }

🚫 过滤特殊字符

function filterCharacter(str){
        // 首先设置一个模式
        let pattern = new RegExp("[`~!@#$^&*()=:”“'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;]")
        let resultStr = "";
        for (let i = 0; i < str.length; i++) {
            // 主要通过 replace ,pattern 规则 去把字符替换成空 最后拼接在 resultStr
            resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
        }
        // 当循环结束的时候返回最后结果 resultStr
        return resultStr;
    }
    
    // 示例
filterCharacter('gyaskjdhy12316789#$%^&!@#1=123,./[') // 结果:gyaskjdhy123167891123

❗常用正则判断

// 校验2-9位文字 不符合为 false  符合为 true
const validateName = (name) => {
  const reg = /^[\u4e00-\u9fa5]{2,9}$/;
  return reg.test(name);
};

// 校验手机号
const validatePhoneNum = (mobile) => {
  const reg = /^1[3,4,5,6,7,8,9]\d{9}$/;
  return reg.test(mobile);
};

// 校验6到18位大小写字母数字下划线组成的密码
const validatePassword = (password) => {
  const reg = /^[a-zA-Z0-9_]{6,18}$/;
  return reg.test(password);
};

🕐时间相关

//获取当前时间年月日
getCurrentTime() {
      var currentDate = new Date();
      return (
        currentDate.getFullYear() +
        "-" +
        (currentDate.getMonth() + 1) +
        "-" +
        currentDate.getDate()
      );
}
//获取当前时间年月日时分秒
getCurrentTime() {
      var date = new Date(); //当前时间
      var year = date.getFullYear(); //返回指定日期的年份
      var month = this.repair(date.getMonth() + 1); //月
      var day = this.repair(date.getDate()); //日
      var hour = this.repair(date.getHours()); //时
      var minute = this.repair(date.getMinutes()); //分
      var second = this.repair(date.getSeconds()); //秒

      //当前时间
      var curTime =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        ":" +
        minute +
        ":" +
        second;
      return curTime;
}

// 获取前n天日期
function getBeforeDate=()=>{
  var n = n;
  var d = new Date();
  var year = d.getFullYear();
  var mon = d.getMonth() + 1;
  var day = d.getDate();
  if (day <= n) {
    if (mon > 1) {
      mon = mon - 1;
    } else {
      year = year - 1;
      mon = 12;
    }
  }
  d.setDate(d.getDate() - n);
  year = d.getFullYear();
  mon = d.getMonth() + 1;
  day = d.getDate();
  const s = year + '-' + (mon < 10 ? '0' + mon : mon) + '-' + (day < 10 ? '0' + day : day);
  return s;
}
//根据不同时间的消息,输出不同的时间格式
toggleTime(date) {
      var time;
      var type = this.getDateDiff(date);
      //1:新消息,2:当天消息,3:昨天消息,4:今年消息,5:其他消息
      if (type == 1) {
        time = "刚刚"; //新消息,不显示时间,但是要显示"以下为最新消息"
      } else if (type == 2) {
        time = dayjs(date).format("H:mm"); //当天消息,显示:10:22
      } else if (type == 3) {
        time = dayjs(date).format("昨天 H:mm"); //昨天消息,显示:昨天 20:41
      } else if (type == 4) {
        time = dayjs(date)
          .format("M月D日 AH:mm")
          .replace("AM", "上午")
          .replace("PM", "下午"); //今年消息,上午下午,显示:3月17日 下午16:45
      } else if (type == 5) {
        time = dayjs(date)
          .format("YYYY年M月D日 AH:mm")
          .replace("AM", "上午")
          .replace("PM", "下午"); //其他消息,上午下午,显示:2020年11月2日 下午15:17
      }
      return time;
}
//判断消息类型
getDateDiff(date) {
      var nowDate = dayjs(new Date()); //当前时间
      var oldDate = dayjs(new Date(date)); //参数时间
      var result;
      if (nowDate.year() - oldDate.year() >= 1) {
        result = 5;
      } else if (
        nowDate.month() - oldDate.month() >= 1 ||
        nowDate.date() - oldDate.date() >= 2
      ) {
        result = 4;
      } else if (nowDate.date() - oldDate.date() >= 1) {
        result = 3;
      } else if (
        nowDate.hour() - oldDate.hour() >= 1 ||
        nowDate.minute() - oldDate.minute() >= 5
      ) {
        result = 2;
      } else {
        result = 1;
      }
      return result;
}
//根据两个日期,判断相差天数
function daysBetween = (sDate1, sDate2) => {
  var time1 = Date.parse(new Date(sDate1));
  var time2 = Date.parse(new Date(sDate2));
  var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
  return nDays;
}
//时间戳转换时间
function getdate= (date) => {
  var now = new Date(date),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + now.toTimeString().substr(0, 8);
}
/**
 * 获取本周周一和周日日期
 */
getCurrentWeek() {
  const start = moment().weekday(1).format('YYYY-MM-DD'); //本周一
  const end = moment().weekday(7).format('YYYY-MM-DD'); //本周日
  return [start, end]
},

/**
 * 获取前 i 周的周一和周日日期,并以数组的方式返回。
 * 当 i=1,获取的是上周一和上周日的日期;
 * 当 i=2,获取的是上上周一和上上周日的日期
 * ...以此类推
 * @param i
 */
getLastWeek(i) {
  let weekOfDay = parseInt(moment().format('E'));//计算今天是这周第几天
  let last_monday = moment().subtract(weekOfDay + 7 * i - 1, 'days').format('YYYY-MM-DD');//周一日期
  let last_sunday = moment().subtract(weekOfDay + 7 * (i - 1), 'days').format('YYYY-MM-DD');//周日日期
  return [last_monday, last_sunday]
},

/**
 * 获取后 i 周的周一和周日日期,并以数组的方式返回。
 * 当 i=1,获取的是下周一和下周日的日期;
 * 当 i=2,获取的是下下周一和下下周日的日期
 * ...以此类推
 * @param i
 */
getNextWeek(i) {
  let weekOfDay = parseInt(moment().format('E'));//计算今天是这周第几天
  let next_monday = moment().add((7 - weekOfDay) + 7 * (i - 1) + 1, 'days').format('YYYY-MM-DD');//周一日期
  let next_sunday = moment().add((7 - weekOfDay) + 7 * i, 'days').format('YYYY-MM-DD');//周日日期
  return [next_monday, next_sunday]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值