JS生成UUID唯一标识方法

7,654 阅读1分钟

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() 

二、

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() 

三、利用随机数加时间戳

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()  

四、 指定长度和基数

// 指定长度和基数
function getUuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    let uuid = []
    let i
    radix = radix || chars.length
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
        let r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        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)