生成随机数

Huy小于 1 分钟javascriptjavascript

手写封装一个 js 随机数的生成函数:

方式 1:

const randomString = (length) => {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  const charactersLength = characters.length
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

方式 2:

// 仅适用于 11 位以下
const randomString = (length) => {
  return Math.random()
    .toString(36)
    .substring(2, length + 2)
    .padEnd(length, '0')
}
Loading...