常用公用方法,持续更新。。。

171 阅读1分钟

说明

项目中经常会用到的一些小方法总结。整理归纳以便于后期查看。

localStorage处理,sessionStorage同理

export const $localStorage = {
  // 存储
  set(key, value) {
    if (typeOf(value) === 'array' || typeOf(value) === 'object') {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  },
  // 取出数据
  get(key) {
    const content = localStorage.getItem(key);
    try {
      return JSON.parse(content);
    } catch {
      return content;
    }
  },
  // 删除数据
  remove(key) {
    localStorage.removeItem(key);
  }
};

根据时间戳返回天、时、分、秒

export const countdownFormat = (distance) => {
  if (distance > 0) {
    // 天
    const day = Math.floor(distance / 86400000);
    distance -= day * 86400000;
    // 时
    const hour = Math.floor(distance / 3600000);
    distance -= hour * 3600000;
    // 分
    const minute = Math.floor(distance / 60000);
    distance -= minute * 60000;
    // 秒
    const second = Math.floor(distance / 1000);
    distance -= second * 1000;
    return {
      d: parseInt(day / 10) + '' + parseInt(day % 10),
      h: parseInt(hour / 10) + '' + parseInt(hour % 10),
      m: parseInt(minute / 10) + '' + parseInt(minute % 10),
      s: parseInt(second / 10) + '' + parseInt(second % 10)
    };
  } else {
    return {
      d: '00',
      h: '00',
      m: '00',
      s: '00'
    };
  }
};

判断数据类型

export const typeOf = (obj) => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
typeOf(value) === 'array'
typeOf(value) === 'object'

判断是否为同一天

export const isSameDay = (startTime, endTime) => {
  return new Date(startTime).toDateString() === new Date(endTime).toDateString();
};

数字千分位

/**
 * 数字千分位
 * @param {Number|String} number 数字
 * @param {Number|String} fix 保留几位小数 no-按原数据返回
 * @returns 千分位之后的结果
 */
exports.toThousands = function (number, fix = 'no') {
  const numberTemp = fix === 'no' ? String((number || 0)) : Number((number || 0)).toFixed(fix)
  if (isNaN(numberTemp)) return number
  const numArr = numberTemp.split('.')
  const negative = numArr[0].includes('-') ? '-' : ''
  let num = negative === '-' ? numArr[0].substring(1) : numArr[0]
  let result = ''
  while (num.length > 3) {
    result = ',' + num.slice(-3) + result
    num = num.slice(0, num.length - 3)
  }
  num && (result = num + result)
  return `${negative}${result}${numArr[1] ? '.' + numArr[1] : ''}`
}

字符串转json

export const convertToObj = (str) => {
  try {
    return JSON.parse(str);
  } catch {
    return str;
  }
};

setTimeout倒计时

// 1.获取短信验证码
const COUNT_INTERVAL = 1000; // 1秒
const COUNT_SECONDS = 90; // 倒计时秒数
countDownFn(time) {
  const currentTime = Date.now();
  let recursionCount = 0; // 递归次数

  const countDown = () => {
    this.timeClock && clearTimeout(this.timeClock);
    if (time < 0) {
      this.sendCode = false;
      this.sendCodeText = '重新获取';
      clearTimeout(this.timeClock);
      return;
    } else {
      this.sendCode = true;
      this.sendCodeText = `重新获取( ${time}s )`;
      time--;
    }

    // 计算误差
    const offset = Date.now() - (currentTime + recursionCount * COUNT_INTERVAL);
    const nextTime = COUNT_INTERVAL - offset;
    recursionCount++;

    this.timeClock = setTimeout(countDown, nextTime);
  };
  countDown();
}

// 2.显示距活动开始的时间
countDownFn (startTime, endTime) {
  const currentTime = Date.now()
  let recursionCount = 0 // 递归次数

  const countDown = () => {
    this.timerId && clearTimeout(this.timerId);
    this.curTime = Date.now() + this.deltaTime
    if (this.curTime < startTime) {
      const { d, h, m } = countdownFormat(startTime - this.curTime)
      this.tips = `距离比赛时间还有:${d}${h}小时${m}分钟`
    } else if (this.curTime <= endTime) {
      const { d, h, m } = countdownFormat(endTime - this.curTime)
      this.tips = `距离大赛结束还有:${d}${h}小时${m}分钟`
    } else {
      this.tips = `距离大赛结束还有:00天00小时00分钟`
      this.timerId && clearTimeout(this.timerId)
    }

    // 计算误差
    const offset = Date.now() - (currentTime + recursionCount * COUNT_INTERVAL)
    const nextTime = COUNT_INTERVAL - offset
    recursionCount++

    this.timerId = setTimeout(countDown, nextTime)
  }
  countDown()
}

年月日日期前添加0

/**
 * 年月日日期前添加0 2022-3-30-->2022-03-30
 * @param {String} str 日期字符串
 * @returns 格式化后的日期字符串
 */
const datePadZero = function (str) {
  return str.split('-').map(num => padStartZero(num)).join('-')
}

获取前三个月的时间

/**
 * 获取前三个月的时间
 * @returns dateObj { startTime, endTime }
 */
const getLast3Month = function () {
  const now = new Date()
  const year = now.getFullYear()
  let month = now.getMonth() + 1
  const day = now.getDate()
  const dateObj = { startTime: '', endTime: `${year}-${month}-${day}` }

  if (month <= 3) {
    const month3 = 12 - (3 - month)
    const start3MonthDay = new Date((year - 1), month3, 0).getDate() // 3个月前所在月的总天数
    dateObj.startTime = `${year - 1}-${month3}-${start3MonthDay < day ? start3MonthDay : day}`
  } else {
    const endMonthDay = new Date(year, month, 0).getDate() // 当前月的总天数
    const start3MonthDay = new Date(year, month - 3, 0).getDate()
    if (start3MonthDay < day) {
      // day < endMonthDay 主要是针对二月份
      dateObj.startTime = `${year}-${month - 3}-${day < endMonthDay ? (start3MonthDay - (endMonthDay - day)) : start3MonthDay}`
    } else {
      dateObj.startTime = `${year}-${month - 3}-${day}`
    }
  }

  dateObj.startTime = datePadZero(dateObj.startTime)
  dateObj.endTime = datePadZero(dateObj.endTime)
  return dateObj
}

数字前面补0

/**
 * 数字前面补0
 * @param {String|Number} str 字符串或者数字
 * @returns 新的补零字符串
 */
const padStartZero = function (str) {
  return String(str).padStart(2, '0')
}

获取前几天后几天的时间

/**
 * 获取前几天后几天的时间
 * @param {String|Date} date 参照日期
 * @param {Number} day 负数表示前几天,正数表示后几天
 * @returns 返回天数
 */
const getNextDate = function (date, day) {
  const dd = new Date(date)
  dd.setDate(dd.getDate() + day)
  const y = dd.getFullYear()
  const m = padStartZero(dd.getMonth() + 1)
  const d = padStartZero(dd.getDate())
  return `${y}-${m}-${d}`
}

深拷贝

const deepClone = function (obj) {
  if ([null, undefined, NaN, false].includes(obj) || (typeof obj !== 'object' && typeof obj !== 'function')) return obj
  const o = Array.isArray(obj) ? [] : {}
  for (const i in obj) {
    o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
  }
  return o
}

延时

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

随机排列数组

const shuffle = arr => arr.sort(() => 0.5 - Math.random())