Skip to content

开发中最常用的100个工具函数

本文档收集了开发中最常用的100个JavaScript工具函数,涵盖数组、对象、字符串、数字、日期、函数、DOM等多个领域。

数组工具函数

1. 数组去重

javascript
const uniqueArray = arr => [...new Set(arr)]

// 示例
const arr = [1, 2, 2, 3, 4, 4, 5]
console.log(uniqueArray(arr)) // [1, 2, 3, 4, 5]

2. 数组按字段排序

javascript
const sortByField = (arr, field, order = 'asc') => {
  return arr.sort((a, b) => {
    if (a[field] < b[field]) return order === 'asc' ? -1 : 1
    if (a[field] > b[field]) return order === 'asc' ? 1 : -1
    return 0
  })
}

// 示例
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
]
console.log(sortByField(users, 'age')) // 按年龄升序排序

3. 数组扁平化

javascript
const flattenArray = arr => {
  return arr.reduce(
    (acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val),
    []
  )
}

// 示例
const nestedArray = [1, [2, [3, [4, 5]]]]
console.log(flattenArray(nestedArray)) // [1, 2, 3, 4, 5]

4. 数组随机排序

javascript
const shuffleArray = arr => {
  const newArr = [...arr]
  for (let i = newArr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArr[i], newArr[j]] = [newArr[j], newArr[i]]
  }
  return newArr
}

// 示例
const arr = [1, 2, 3, 4, 5]
console.log(shuffleArray(arr)) // 随机排序的数组

5. 数组分组

javascript
const groupBy = (arr, key) => {
  return arr.reduce((acc, item) => {
    const group = item[key]
    if (!acc[group]) {
      acc[group] = []
    }
    acc[group].push(item)
    return acc
  }, {})
}

// 示例
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 }
]
console.log(groupBy(users, 'age')) // 按年龄分组

6. 数组交集

javascript
const intersection = (arr1, arr2) => {
  return arr1.filter(item => arr2.includes(item))
}

// 示例
const arr1 = [1, 2, 3, 4]
const arr2 = [3, 4, 5, 6]
console.log(intersection(arr1, arr2)) // [3, 4]

7. 数组差集

javascript
const difference = (arr1, arr2) => {
  return arr1.filter(item => !arr2.includes(item))
}

// 示例
const arr1 = [1, 2, 3, 4]
const arr2 = [3, 4, 5, 6]
console.log(difference(arr1, arr2)) // [1, 2]

8. 数组并集

javascript
const union = (arr1, arr2) => {
  return [...new Set([...arr1, ...arr2])]
}

// 示例
const arr1 = [1, 2, 3, 4]
const arr2 = [3, 4, 5, 6]
console.log(union(arr1, arr2)) // [1, 2, 3, 4, 5, 6]

9. 数组最大值

javascript
const max = arr => Math.max(...arr)

// 示例
const arr = [1, 5, 3, 9, 2]
console.log(max(arr)) // 9

10. 数组最小值

javascript
const min = arr => Math.min(...arr)

// 示例
const arr = [1, 5, 3, 9, 2]
console.log(min(arr)) // 1

对象工具函数

11. 对象深拷贝

javascript
const deepClone = obj => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 示例
const obj = { name: 'Alice', age: 25, address: { city: 'New York' } }
const clonedObj = deepClone(obj)
console.log(clonedObj) // 深拷贝后的对象

12. 对象合并

javascript
const mergeObjects = (...objects) => {
  return objects.reduce((acc, obj) => {
    return Object.keys(obj).reduce((result, key) => {
      result[key] = obj[key]
      return result
    }, acc)
  }, {})
}

// 示例
const obj1 = { name: 'Alice' }
const obj2 = { age: 25 }
const obj3 = { address: 'New York' }
console.log(mergeObjects(obj1, obj2, obj3)) // 合并后的对象

13. 对象属性检查

javascript
const hasProperty = (obj, property) => {
  return Object.prototype.hasOwnProperty.call(obj, property)
}

// 示例
const obj = { name: 'Alice', age: 25 }
console.log(hasProperty(obj, 'name')) // true
console.log(hasProperty(obj, 'address')) // false

14. 对象属性移除

javascript
const removeProperty = (obj, property) => {
  const newObj = { ...obj }
  delete newObj[property]
  return newObj
}

// 示例
const obj = { name: 'Alice', age: 25, address: 'New York' }
console.log(removeProperty(obj, 'address')) // 移除address属性后的对象

15. 对象转数组

javascript
const objectToArray = obj => {
  return Object.entries(obj).map(([key, value]) => ({ key, value }))
}

// 示例
const obj = { name: 'Alice', age: 25 }
console.log(objectToArray(obj)) // [{ key: 'name', value: 'Alice' }, { key: 'age', value: 25 }]

16. 对象深比较

javascript
const deepCompare = (obj1, obj2) => {
  if (obj1 === obj2) return true
  if (obj1 == null || obj2 == null) return false
  if (typeof obj1 !== typeof obj2) return false
  if (typeof obj1 === 'object') {
    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)
    if (keys1.length !== keys2.length) return false
    for (const key of keys1) {
      if (!deepCompare(obj1[key], obj2[key])) return false
    }
    return true
  }
  return obj1 === obj2
}

// 示例
const obj1 = { name: 'Alice', age: 25, address: { city: 'New York' } }
const obj2 = { name: 'Alice', age: 25, address: { city: 'New York' } }
console.log(deepCompare(obj1, obj2)) // true

17. 对象属性值提取

javascript
const pluck = (arr, property) => {
  return arr.map(item => item[property])
}

// 示例
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
]
console.log(pluck(users, 'name')) // ['Alice', 'Bob']

18. 对象属性映射

javascript
const mapObject = (obj, fn) => {
  return Object.keys(obj).reduce((result, key) => {
    result[key] = fn(obj[key], key)
    return result
  }, {})
}

// 示例
const obj = { a: 1, b: 2, c: 3 }
console.log(mapObject(obj, value => value * 2)) // { a: 2, b: 4, c: 6 }

19. 对象属性过滤

javascript
const filterObject = (obj, fn) => {
  return Object.keys(obj).reduce((result, key) => {
    if (fn(obj[key], key)) {
      result[key] = obj[key]
    }
    return result
  }, {})
}

// 示例
const obj = { a: 1, b: 2, c: 3, d: 4 }
console.log(filterObject(obj, value => value > 2)) // { c: 3, d: 4 }

20. 对象属性遍历

javascript
const forEachObject = (obj, fn) => {
  Object.keys(obj).forEach(key => fn(obj[key], key))
}

// 示例
const obj = { name: 'Alice', age: 25 }
forEachObject(obj, (value, key) => console.log(`${key}: ${value}`))

字符串工具函数

21. 字符串首字母大写

javascript
const capitalize = str => {
  if (!str) return ''
  return str.charAt(0).toUpperCase() + str.slice(1)
}

// 示例
console.log(capitalize('hello')) // Hello

22. 字符串全大写

javascript
const toUpperCase = str => str.toUpperCase()

// 示例
console.log(toUpperCase('hello')) // HELLO

23. 字符串全小写

javascript
const toLowerCase = str => str.toLowerCase()

// 示例
console.log(toLowerCase('HELLO')) // hello

24. 字符串去除空格

javascript
const trim = str => str.trim()

// 示例
console.log(trim('  hello world  ')) // hello world

25. 字符串去除左侧空格

javascript
const trimLeft = str => str.trimLeft()

// 示例
console.log(trimLeft('  hello world')) // hello world

26. 字符串去除右侧空格

javascript
const trimRight = str => str.trimRight()

// 示例
console.log(trimRight('hello world  ')) // hello world

27. 字符串分割

javascript
const split = (str, separator) => str.split(separator)

// 示例
console.log(split('hello world', ' ')) // ['hello', 'world']

28. 字符串替换

javascript
const replace = (str, search, replacement) => str.replace(search, replacement)

// 示例
console.log(replace('hello world', 'world', 'JavaScript')) // hello JavaScript

29. 字符串替换所有

javascript
const replaceAll = (str, search, replacement) => {
  return str.split(search).join(replacement)
}

// 示例
console.log(replaceAll('hello world world', 'world', 'JavaScript')) // hello JavaScript JavaScript

30. 字符串包含检查

javascript
const includes = (str, substring) => str.includes(substring)

// 示例
console.log(includes('hello world', 'world')) // true

31. 字符串起始检查

javascript
const startsWith = (str, prefix) => str.startsWith(prefix)

// 示例
console.log(startsWith('hello world', 'hello')) // true

32. 字符串结束检查

javascript
const endsWith = (str, suffix) => str.endsWith(suffix)

// 示例
console.log(endsWith('hello world', 'world')) // true

33. 字符串长度

javascript
const length = str => str.length

// 示例
console.log(length('hello world')) // 11

34. 字符串截取

javascript
const substring = (str, start, end) => str.substring(start, end)

// 示例
console.log(substring('hello world', 0, 5)) // hello

35. 字符串重复

javascript
const repeat = (str, times) => str.repeat(times)

// 示例
console.log(repeat('hello', 3)) // hellohellohello

36. 字符串反转

javascript
const reverse = str => str.split('').reverse().join('')

// 示例
console.log(reverse('hello')) // olleh

37. 字符串驼峰转换

javascript
const camelCase = str => {
  return str.replace(/-([a-z])/g, g => g[1].toUpperCase())
}

// 示例
console.log(camelCase('hello-world')) // helloWorld

38. 字符串连字符转换

javascript
const kebabCase = str => {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

// 示例
console.log(kebabCase('helloWorld')) // hello-world

39. 字符串 Pascal 转换

javascript
const pascalCase = str => {
  return str.replace(/(^|[-_])([a-z])/g, (_, __, c) => c.toUpperCase())
}

// 示例
console.log(pascalCase('hello-world')) // HelloWorld

40. 字符串格式化

javascript
const format = (str, ...args) => {
  return str.replace(/\{([0-9]+)\}/g, (match, index) => args[index] || '')
}

// 示例
console.log(format('Hello {0}, you are {1} years old', 'Alice', 25)) // Hello Alice, you are 25 years old

数字工具函数

41. 数字格式化

javascript
const formatNumber = (num, decimals = 2) => {
  return num.toFixed(decimals)
}

// 示例
console.log(formatNumber(123.456)) // 123.46

42. 数字千分位格式化

javascript
const formatThousands = num => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 示例
console.log(formatThousands(1234567)) // 1,234,567

43. 数字范围检查

javascript
const isInRange = (num, min, max) => {
  return num >= min && num <= max
}

// 示例
console.log(isInRange(5, 1, 10)) // true

44. 数字取整

javascript
const round = num => Math.round(num)

// 示例
console.log(round(123.456)) // 123

45. 数字向上取整

javascript
const ceil = num => Math.ceil(num)

// 示例
console.log(ceil(123.456)) // 124

46. 数字向下取整

javascript
const floor = num => Math.floor(num)

// 示例
console.log(floor(123.456)) // 123

47. 数字绝对值

javascript
const abs = num => Math.abs(num)

// 示例
console.log(abs(-123)) // 123

48. 数字幂运算

javascript
const power = (base, exponent) => Math.pow(base, exponent)

// 示例
console.log(power(2, 3)) // 8

49. 数字平方根

javascript
const sqrt = num => Math.sqrt(num)

// 示例
console.log(sqrt(9)) // 3

50. 随机数生成

javascript
const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 示例
console.log(random(1, 10)) // 1-10之间的随机数

日期工具函数

51. 获取当前日期

javascript
const getCurrentDate = () => new Date()

// 示例
console.log(getCurrentDate()) // 当前日期时间

52. 日期格式化

javascript
const formatDate = (date, format = 'YYYY-MM-DD') => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 示例
console.log(formatDate(new Date())) // 2026-03-31

53. 日期差值计算

javascript
const getDateDiff = (date1, date2) => {
  const diffTime = Math.abs(date2 - date1)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 示例
const date1 = new Date('2026-03-01')
const date2 = new Date('2026-03-31')
console.log(getDateDiff(date1, date2)) // 30

54. 日期加减

javascript
const addDays = (date, days) => {
  const result = new Date(date)
  result.setDate(result.getDate() + days)
  return result
}

// 示例
const date = new Date('2026-03-31')
console.log(formatDate(addDays(date, 7))) // 2026-04-07

55. 判断是否是今天

javascript
const isToday = date => {
  const today = new Date()
  return (
    date.getDate() === today.getDate() &&
    date.getMonth() === today.getMonth() &&
    date.getFullYear() === today.getFullYear()
  )
}

// 示例
console.log(isToday(new Date())) // true

56. 判断是否是闰年

javascript
const isLeapYear = year => {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}

// 示例
console.log(isLeapYear(2024)) // true
console.log(isLeapYear(2025)) // false

57. 获取月份天数

javascript
const getDaysInMonth = (year, month) => {
  return new Date(year, month, 0).getDate()
}

// 示例
console.log(getDaysInMonth(2026, 3)) // 31 (3月有31天)

58. 获取星期几

javascript
const getDayOfWeek = date => {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return days[date.getDay()]
}

// 示例
console.log(getDayOfWeek(new Date())) // 当前星期几

59. 时间戳转换为日期

javascript
const timestampToDate = timestamp => {
  return new Date(timestamp)
}

// 示例
console.log(timestampToDate(Date.now())) // 当前日期

60. 日期转换为时间戳

javascript
const dateToTimestamp = date => {
  return date.getTime()
}

// 示例
console.log(dateToTimestamp(new Date())) // 当前时间戳

函数工具函数

61. 函数防抖

javascript
const debounce = (func, wait) => {
  let timeout
  return function () {
    const context = this
    const args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}

// 示例
const debouncedFunction = debounce(() => {
  console.log('Debounced function called')
}, 1000)

62. 函数节流

javascript
const throttle = (func, limit) => {
  let inThrottle
  return function () {
    const context = this
    const args = arguments
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

// 示例
const throttledFunction = throttle(() => {
  console.log('Throttled function called')
}, 1000)

63. 函数柯里化

javascript
const curry = func => {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args)
    } else {
      return function (...moreArgs) {
        return curried.apply(this, args.concat(moreArgs))
      }
    }
  }
}

// 示例
const add = (a, b, c) => a + b + c
const curriedAdd = curry(add)
console.log(curriedAdd(1)(2)(3)) // 6

64. 函数组合

javascript
const compose = (...funcs) => {
  return funcs.reduce(
    (a, b) =>
      (...args) =>
        a(b(...args))
  )
}

// 示例
const double = x => x * 2
const square = x => x * x
const composedFunction = compose(square, double)
console.log(composedFunction(5)) // (5 * 2)² = 100

65. 函数重试

javascript
const retry = (func, retries = 3, delay = 1000) => {
  return new Promise((resolve, reject) => {
    const attempt = count => {
      func()
        .then(resolve)
        .catch(error => {
          if (count < retries) {
            setTimeout(() => attempt(count + 1), delay)
          } else {
            reject(error)
          }
        })
    }
    attempt(0)
  })
}

// 示例
const fetchData = () => {
  return new Promise((resolve, reject) => {
    if (Math.random() > 0.5) {
      resolve('Data fetched successfully')
    } else {
      reject('Failed to fetch data')
    }
  })
}

retry(fetchData, 3, 1000).then(console.log).catch(console.error)

66. 函数计时

javascript
const time = func => {
  const start = performance.now()
  const result = func()
  const end = performance.now()
  console.log(`Execution time: ${end - start}ms`)
  return result
}

// 示例
const heavyFunction = () => {
  let sum = 0
  for (let i = 0; i < 1000000; i++) {
    sum += i
  }
  return sum
}

time(heavyFunction) // 输出执行时间

67. 函数缓存

javascript
const memoize = func => {
  const cache = {}
  return function (...args) {
    const key = JSON.stringify(args)
    if (cache[key]) {
      return cache[key]
    }
    const result = func.apply(this, args)
    cache[key] = result
    return result
  }
}

// 示例
const fibonacci = memoize(n => {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
})

console.log(fibonacci(40)) // 计算速度会快很多

68. 函数绑定

javascript
const bind = (func, context, ...args) => {
  return function (...moreArgs) {
    return func.apply(context, args.concat(moreArgs))
  }
}

// 示例
const obj = { name: 'Alice' }
const greet = function (greeting) {
  console.log(`${greeting}, ${this.name}!`)
}

const boundGreet = bind(greet, obj, 'Hello')
boundGreet() // Hello, Alice!

69. 函数延迟执行

javascript
const delay = (func, wait, ...args) => {
  return setTimeout(() => func.apply(null, args), wait)
}

// 示例
delay(() => {
  console.log('Delayed function called')
}, 1000)

70. 函数批量执行

javascript
const batch = funcs => {
  return funcs.map(func => func())
}

// 示例
const func1 = () => 'Result 1'
const func2 = () => 'Result 2'
const func3 = () => 'Result 3'

console.log(batch([func1, func2, func3])) // ['Result 1', 'Result 2', 'Result 3']

DOM 工具函数

71. DOM 元素选择

javascript
const $ = (selector, context = document) => {
  return context.querySelector(selector)
}

// 示例
const element = $('#myElement')

72. DOM 元素选择所有

javascript
const $$ = (selector, context = document) => {
  return Array.from(context.querySelectorAll(selector))
}

// 示例
const elements = $$('.myClass')

73. DOM 元素创建

javascript
const createElement = (tagName, options = {}) => {
  const element = document.createElement(tagName)
  Object.assign(element, options)
  return element
}

// 示例
const div = createElement('div', { className: 'myClass', innerText: 'Hello' })

74. DOM 元素添加

javascript
const appendChild = (parent, child) => {
  parent.appendChild(child)
}

// 示例
const parent = $('#parent')
const child = createElement('div', { innerText: 'Child' })
appendChild(parent, child)

75. DOM 元素移除

javascript
const removeChild = (parent, child) => {
  parent.removeChild(child)
}

// 示例
const parent = $('#parent')
const child = $('#child')
removeChild(parent, child)

76. DOM 元素属性设置

javascript
const setAttribute = (element, attribute, value) => {
  element.setAttribute(attribute, value)
}

// 示例
const element = $('#myElement')
setAttribute(element, 'data-id', '123')

77. DOM 元素属性获取

javascript
const getAttribute = (element, attribute) => {
  return element.getAttribute(attribute)
}

// 示例
const element = $('#myElement')
console.log(getAttribute(element, 'data-id'))

78. DOM 元素样式设置

javascript
const setStyle = (element, styles) => {
  Object.assign(element.style, styles)
}

// 示例
const element = $('#myElement')
setStyle(element, { color: 'red', fontSize: '16px' })

79. DOM 元素类名添加

javascript
const addClass = (element, className) => {
  element.classList.add(className)
}

// 示例
const element = $('#myElement')
addClass(element, 'active')

80. DOM 元素类名移除

javascript
const removeClass = (element, className) => {
  element.classList.remove(className)
}

// 示例
const element = $('#myElement')
removeClass(element, 'active')

81. DOM 元素类名切换

javascript
const toggleClass = (element, className) => {
  element.classList.toggle(className)
}

// 示例
const element = $('#myElement')
toggleClass(element, 'active')

82. DOM 元素事件监听

javascript
const addEventListener = (element, event, handler) => {
  element.addEventListener(event, handler)
}

// 示例
const button = $('#myButton')
addEventListener(button, 'click', () => {
  console.log('Button clicked')
})

83. DOM 元素事件移除

javascript
const removeEventListener = (element, event, handler) => {
  element.removeEventListener(event, handler)
}

// 示例
const button = $('#myButton')
const handler = () => console.log('Button clicked')
addEventListener(button, 'click', handler)
// 稍后移除事件
removeEventListener(button, 'click', handler)

84. DOM 元素滚动到顶部

javascript
const scrollToTop = element => {
  element.scrollTop = 0
}

// 示例
const container = $('#container')
scrollToTop(container)

85. DOM 元素滚动到底部

javascript
const scrollToBottom = element => {
  element.scrollTop = element.scrollHeight
}

// 示例
const container = $('#container')
scrollToBottom(container)

Promise 工具函数

86. Promise 延迟

javascript
const delayPromise = ms => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

// 示例
delayPromise(1000).then(() => {
  console.log('1 second later')
})

87. Promise 并行执行

javascript
const parallel = promises => {
  return Promise.all(promises)
}

// 示例
const promise1 = Promise.resolve(1)
const promise2 = Promise.resolve(2)
const promise3 = Promise.resolve(3)

parallel([promise1, promise2, promise3]).then(console.log) // [1, 2, 3]

88. Promise 串行执行

javascript
const series = funcs => {
  return funcs.reduce((promise, func) => {
    return promise.then(results => {
      return func().then(result => [...results, result])
    })
  }, Promise.resolve([]))
}

// 示例
const func1 = () => Promise.resolve(1)
const func2 = () => Promise.resolve(2)
const func3 = () => Promise.resolve(3)

series([func1, func2, func3]).then(console.log) // [1, 2, 3]

89. Promise 超时处理

javascript
const withTimeout = (promise, timeout, errorMessage = 'Promise timed out') => {
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      setTimeout(() => reject(new Error(errorMessage)), timeout)
    })
  ])
}

// 示例
const longRunningPromise = new Promise(resolve => {
  setTimeout(() => resolve('Success'), 2000)
})

withTimeout(longRunningPromise, 1000).then(console.log).catch(console.error) // 会超时

90. Promise 错误处理

javascript
const handleError = (promise, fallback) => {
  return promise.catch(() => fallback)
}

// 示例
const failingPromise = Promise.reject('Error')
handleError(failingPromise, 'Fallback value').then(console.log) // Fallback value

验证工具函数

91. 邮箱验证

javascript
const isValidEmail = email => {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return regex.test(email)
}

// 示例
console.log(isValidEmail('test@example.com')) // true
console.log(isValidEmail('invalid-email')) // false

92. 手机号验证

javascript
const isValidPhone = phone => {
  const regex = /^1[3-9]\d{9}$/
  return regex.test(phone)
}

// 示例
console.log(isValidPhone('13812345678')) // true
console.log(isValidPhone('12345678901')) // false

93. URL 验证

javascript
const isValidUrl = url => {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

// 示例
console.log(isValidUrl('https://www.example.com')) // true
console.log(isValidUrl('invalid-url')) // false

94. 身份证号验证

javascript
const isValidIdCard = idCard => {
  const regex =
    /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  return regex.test(idCard)
}

// 示例
console.log(isValidIdCard('110101199001011234')) // true
console.log(isValidIdCard('123456789012345678')) // false

95. 密码强度验证

javascript
const isStrongPassword = password => {
  // 至少8位,包含大小写字母和数字
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/
  return regex.test(password)
}

// 示例
console.log(isStrongPassword('Password123')) // true
console.log(isStrongPassword('weak')) // false

其他工具函数

96. 本地存储设置

javascript
const setLocalStorage = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value))
}

// 示例
setLocalStorage('user', { name: 'Alice', age: 25 })

97. 本地存储获取

javascript
const getLocalStorage = key => {
  const value = localStorage.getItem(key)
  return value ? JSON.parse(value) : null
}

// 示例
console.log(getLocalStorage('user')) // { name: 'Alice', age: 25 }

98. 本地存储删除

javascript
const removeLocalStorage = key => {
  localStorage.removeItem(key)
}

// 示例
removeLocalStorage('user')

99. 会话存储设置

javascript
const setSessionStorage = (key, value) => {
  sessionStorage.setItem(key, JSON.stringify(value))
}

// 示例
setSessionStorage('temp', { data: 'temporary' })

100. 会话存储获取

javascript
const getSessionStorage = key => {
  const value = sessionStorage.getItem(key)
  return value ? JSON.parse(value) : null
}

// 示例
console.log(getSessionStorage('temp')) // { data: 'temporary' }

基于 VitePress 的本地知识库