js如何生成唯一标识符UUID

JavaScript013

js如何生成唯一标识符UUID,第1张

可以用这个方法

function generateUUID() {

var d = new Date().getTime(),

uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {

var r = (d + Math.random()*16)%16 | 0

d = Math.floor(d/16)

return (c=='x' ? r : (r&0x3|0x8)).toString(16)

})

return uuid

}

Javascript生成唯一字符串就是 guid:

全局唯一标识符(GUID,Globally Unique Identifier)也称作 UUID(Universally Unique IDentifier) 。

GUID是一种由算法生成的二进制长度为128位的数字标识符。GUID 的格式为“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,其中的 x 是 0-9 或 a-f 范围内的一个32位十六进制数。在理想情况下,任何计算机和计算机集群都不会生成两个相同的GUID。

GUID 的总数达到了2^128(3.4×10^38)个,所以随机生成两个相同GUID的可能性非常小,但并不为0。GUID一词有时也专指微软对UUID标准的实现。

算法实现:

function uuid() {

    var s = []

    var hexDigits = "0123456789abcdef"

    for (var i = 0 i < 36 i++) {

        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)

    }

    s[14] = "4"  // bits 12-15 of the time_hi_and_version field to 0010

    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    s[8] = s[13] = s[18] = s[23] = "-"

 

    var uuid = s.join("")

    return uuid

}

唯一标识符,可用作对象的唯一属性值

// Here are two symbols with the same description:

console.log(Sym1===Sym2)// returns "false"// Symbols are guaranteed to be unique.// Even if we create many symbols with the same description,// they are different values.