【js方法】常用方法封装

项目中常用的方法封装,后续会持续补充。

1. 时间格式化

function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// Examples  
parseTime(new Date(), '{y}年{m}月{d}日 周{a} {h}:{i}:{s}')  // 2024年12月26日 周四 09:32:17

2. 获取url参数

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );
  
// Examples  
getURLParameters('http://url.com/page?n=Adam&s=Smith')  // {n: 'Adam', s: 'Smith'} 

3. 计算2个日期之间的间隔

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)

// Examples 
dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519

4. 请求2个数组的并集,交集,差集,去掉重复项

// 请求2个数组的并集,交集,差集, 去掉重复项
const arr1 = [33, 22, 22, 55, 33, 11, 33, 5]
const arr2 = [22, 22, 55, 77, 88, 88, 99, 99]

// 并集
const union = (arr1, arr2) => Array.from(new Set([...arr1, ...arr2]))
// 交集
const cross = (arr1, arr2) => Array.from(new Set(arr1.filter(item => arr2.includes(item))))
// 单向差集
const singleDiff = (arr1, arr2) => Array.from(new Set(arr1.filter(item => !arr2.includes(item))))
// 双向差集
const bothDiff = (arr1, arr2) => {
  // 找到 arr1 中独有的元素
  const diff1 = Array.from(new Set(arr1.filter(item => !arr2.includes(item))))
  // 找到 arr2 中独有的元素
  const diff2 = Array.from(new Set(arr2.filter(item => !arr1.includes(item))))
  // 合并两个差集
  return [...new Set([...diff1, ...diff2])]
}

// Examples 
console.log(union(arr1, arr2))
console.log(cross(arr1, arr2))
console.log(singleDiff(arr1, arr2))
console.log(bothDiff(arr1, arr2))

5. 校验数据类型

function typeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

// Examples 
typeOf('树哥')  // string
typeOf([])  // array
typeOf(new Date())  // date
typeOf(null) // null
typeOf(true) // boolean
typeOf(() => { }) // function

6. 手机号脱敏

function phoneMask(phone) {
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// Examples 
phoneMask('13913913913')  // 139****3913
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值