JavaScript 工具库:常用函数的封装与应用

34 阅读5分钟

JavaScript 工具库:常用函数的封装与应用

在日常的前端开发中,我们经常会遇到需要进行字符串、日期、对象处理等常见任务。为了提高开发效率,编写一系列常用工具函数库是一种不错的选择。本文将介绍一个简单的 JavaScript 工具库,涵盖了一些常见的功能和应用场景。

1. 时间处理函数

1.1 formatDate(cellValue)

该函数用于将日期时间转换为更易读的格式。通常在表格中显示时间时,我们需要将时间戳格式化为用户友好的字符串,例如:2024-12-24 14:32:10

export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
应用场景
  • 在表格中展示数据库返回的时间戳数据。
  • 实现日期的格式化,确保显示为一致的标准格式。

1.2 formatTime(time, option)

该函数用于将时间转换为相对时间(如“刚刚”、“1分钟前”),或者格式化为指定的日期时间格式。非常适用于社交应用或者展示发布时间的场景。


export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
应用场景
  • 在新闻网站、社交平台等显示动态时,常常用到相对时间格式。
  • 用于用户评论时间的展示。

2. URL 和查询参数处理

2.1 getQueryObject(url)

该函数用于从 URL 中提取查询参数,并返回一个对象。它在处理用户分享的链接或者通过 URL 传递参数时非常有用。

export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}
应用场景
  • 解析用户点击的链接,获取 URL 中的查询参数。
  • 在多页面应用中,通过 URL 参数进行状态传递。

2.2 param(json)

该函数用于将一个对象转化为 URL 查询字符串,非常适合在发送请求时附带查询参数。

export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}
应用场景
  • 在发起 AJAX 请求时将请求参数转换为查询字符串。
  • 实现分页功能时,将当前页数和每页数量作为参数传递。

3. 字符串和数组处理

3.1 byteLength(str)

该函数用于计算一个字符串在 UTF-8 编码下的字节长度。它可以帮助我们处理需要控制字节数的场景,例如在表单输入或文件上传时限制字节数。

export function byteLength(str) {
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}
应用场景
  • 实现文件上传时对文件名或内容的字节长度限制。
  • 在后台验证输入内容的长度。

3.2 cleanArray(actual)

该函数用于清除数组中的空值。适合于处理表单提交时,去除无效数据。

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}
应用场景
  • 在处理用户输入时,移除空值或无效项。
  • 清洗数据,避免空值干扰后续处理。

3.3 uniqueArr(arr)

该函数用于去除数组中的重复项,返回一个新数组。非常适用于处理用户选择的列表,确保每个项目只出现一次。

export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}
应用场景
  • 去除用户选中的重复项。
  • 处理从后台返回的含有重复数据的数组。

4. 对象操作

4.1 objectMerge(target, source)

该函数用于深度合并两个对象。它会递归合并嵌套的对象属性。适用于合并配置对象或状态对象。

export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}
应用场景
  • 合并多个配置对象,确保后面的配置覆盖前面的配置。
  • 合并复杂的数据结构,保持嵌套结构不变。

4.2 deepClone(source)

该函数用于深度克隆一个对象,避免对原对象的引用操作影响克隆对象。适用于需要保持数据不变的场景。

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
应用场景
  • 克隆配置对象,避免修改原始配置。
  • 在状态管理中克隆对象,防止状态直接引用。

5. HTML 操作

5.1 html2Text(val)

该函数将 HTML 字符串转换为纯文本。适用于从 HTML 格式中提取可读的文本内容。

export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}
应用场景
  • 提取文章或评论中的纯文本,去除 HTML 标签。
  • 从富文本编辑器中获取用户输入的文本。

6. 其他实用功能

6.1 debounce(func, wait, immediate)

该函数用于防抖处理,在一定时间内只触发一次事件。适用于输入框输入、窗口尺寸调整等频繁触发的事件。

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result
  const later = function() {
    const last = +new Date() - timestamp
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}
应用场景
  • 防止用户输入过于频繁时,触发重复的请求或计算。
  • 窗口大小调整时,只在调整结束时执行处理。

7. 结语

这个工具库封装了多个常见的功能,可以帮助开发者提高效率,简化代码。你可以根据自己的需求进行修改和扩展,方便在项目中进行复用。在前端开发中,这些函数几乎能应对大多数常见场景,提升项目的可维护性和开发速度。