Create GUID / UUID in JavaScript?

2018-12-30 22:45发布

I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc..

The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.

30条回答
与风俱净
2楼-- · 2018-12-30 23:27
var uniqueId = Math.random().toString(36).substring(2) 
               + (new Date()).getTime().toString(36);

If ID's are generated more than 1 millisecond apart, they are 100% unique.

If two ID's are generated at shorter intervals, and assuming that the random method is truly random, this would generate ID's that are 99.99999999999999% likely to be globally unique (collision in 1 of 10^15)

You can increase this number by adding more digits, but to generate 100% unique ID's you will need to use a global counter.

document.getElementById("unique").innerHTML =
  Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
<div id="unique">
</div>

查看更多
梦寄多情
3楼-- · 2018-12-30 23:27

There is a jQuery plugin that handles Guid's nicely @ http://plugins.jquery.com/project/GUID_Helper

jQuery.Guid.Value()

Returns value of internal Guid. If no guid has been specified, returns a new one (value is then stored internally).


jQuery.Guid.New()

Returns a new Guid and sets it's value internally.


jQuery.Guid.Empty()

Returns an empty Guid 00000000-0000-0000-0000-000000000000.


jQuery.Guid.IsEmpty()

Returns boolean. True if empty/undefined/blank/null.


jQuery.Guid.IsValid()

Returns boolean. True valid guid, false if not.


jQuery.Guid.Set()

Retrns Guid. Sets Guid to user specified Guid, if invalid, returns an empty guid.

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-30 23:28

There have been a couple attempts at this. The question is: do you want actual GUIDs, or just random numbers that look like GUIDs? It's easy enough to generate random numbers.

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

However, note that such values are not genuine GUIDs.

Note: the provided code snippet does not follow RFC4122 which requires that the version (4) has to be integrated into the generated output string. Do not use this answer if you need compliant GUIDs.

Use:

var uuid = guid();

Demo:

function guid() {
  return "ss-s-s-s-sss".replace(/s/g, s4);
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
}

document.getElementById('jsGenId').addEventListener('click', function() {
  document.getElementById('jsIdResult').value = guid();
})
input { font-family: monospace; }
<button id="jsGenId" type="button">Generate GUID</button>
<br>
<input id="jsIdResult" type="text" placeholder="Results will be placed here..." readonly size="40"/>

查看更多
孤独总比滥情好
5楼-- · 2018-12-30 23:28

A web service would be useful.

Quick Google found: http://www.hoskinson.net/GuidGenerator/

Can't vouch for this implementation, but SOMEONE must publish a bonafide GUID generator.

With such a web service, you could develop a REST web interface that consumes the GUID web service, and serves it through AJAX to javascript in a browser.

查看更多
浅入江南
6楼-- · 2018-12-30 23:29

I really like how clean Broofa's answer is, but it's unfortunate that poor implementations of Math.random leave the chance for collision.

Here's a similar RFC4122 version 4 compliant solution that solves that issue by offsetting the first 13 hex numbers by a hex portion of the timestamp. That way, even if Math.random is on the same seed, both clients would have to generate the UUID at the exact same millisecond (or 10,000+ years later) to get the same UUID:

function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return '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);
    });
}


Here's a fiddle to test.

查看更多
高级女魔头
7楼-- · 2018-12-30 23:30

Here's some code based on RFC 4122, section 4.4 (Algorithms for Creating a UUID from Truly Random or Pseudo-Random Number).

function createUUID() {
    // http://www.ietf.org/rfc/rfc4122.txt
    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;
}
查看更多
登录 后发表回答