JS生成UUID唯一标识方法

UUID的编码规则:

1)1~8位采用系统时间,在系统时间上精确到毫秒级保证时间上的惟一性;
2)9~16位采用底层的IP地址,在服务器集群中的惟一性;
3)17~24位采用当前对象的HashCode值,在一个内部对象上的惟一性;
4)25~32位采用调用方法的一个随机数,在一个对象内的毫秒级的惟一性。
通过以上4种策略可以保证惟一性。在系统中需要用到随机数的地方都可以考虑采用UUID算法。

一:

function getUuid () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },
getUuid() // "7cb5a8fe-876a-495c-8b0d-99e413d7373b"

二:

function buildUUID () {
      const hexList = []
      for (let i = 0; i <= 15; i++) {
        hexList[i] = i.toString(16)
      }
      let uuid = ''
      for (let i = 1; i <= 36; i++) {
        if (i === 9 || i === 14 || i === 19 || i === 24) {
          uuid += '-'
        } else if (i === 15) {
          uuid += 4
        } else if (i === 20) {
          uuid += hexList[(Math.random() * 4) | 8]
        } else {
          uuid += hexList[(Math.random() * 16) | 0]
        }
      }
      return uuid.replace(/-/g, '')
    }

buildUUID()  // 'c15f49b872934e2c90fb90b5fd4f6379'

三:利用随机数加时间戳

function buildShortUUID () {
      let unique = 0
      const time = Date.now()
      const random = Math.floor(Math.random() * 1000000000)
      // eslint-disable-next-line no-undef
      unique++
      return random + unique + String(time)
    }

buildShortUUID()  // '301882341657003878583'

四:指定长度和基数

// 指定长度和基数
function getUuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    let uuid = []
    let i
    radix = radix || chars.length

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
        // rfc4122, version 4 form
        let r

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
            }
        }
    }

    return uuid.join('')
}
getUuid(16, 16) // '277571702EE33E11'

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值