生成唯一ID的最佳方法客户端(使用Javascript)

我需要在浏览器中生成唯一的ID。 目前,我正在使用这个:

Math.floor(Math.random() * 10000000000000001) 

我想使用当前的UNIX时间( (new Date).getTime() ),但我担心如果两个客户端在同一时间生成id,它们将不是唯一的。

我可以使用当前的UNIX时间(我想这样,因为这种方式会存储更多信息)? 如果没有,最好的方法是什么(可能是UNIX时间+ 2个随机数字?)

您可以使用以下链接创建GUID:

http://softwareas.com/guid0-a-javascript-guid-generator

在JavaScript中创建GUID / UUID?

这将最大化你“独特性”的机会。

或者,如果它是安全页面,您可以将日期/时间与用户名连接起来,以防止多个同时生成的值。

https://github.com/broofa/node-uuid根据时间戳或随机#提供符合RFC的UUID。 单个文件没有依赖关系,支持时间戳或随机的基于#UU的UUID,如果可用,则使用本机API加密质量随机数,以及其他好东西。

在现代浏览器中,您可以使用加密 :

 var array = new Uint32Array(1); window.crypto.getRandomValues(array); console.log(array); 
 var c = 1; function cuniq() { var d = new Date(), m = d.getMilliseconds() + "", u = ++d + m + (++c === 10000 ? (c = 1) : c); return u; } 

这是我生成guid的javascript代码。 它执行快速hex映射并且非常有效:

 AuthenticationContext.prototype._guid = function () { // RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or // pseudo-random numbers. // The algorithm is as follows: // Set the two most significant bits (bits 6 and 7) of the // clock_seq_hi_and_reserved to zero and one, respectively. // Set the four most significant bits (bits 12 through 15) of the // time_hi_and_version field to the 4-bit version number from // Section 4.1.3. Version4 // Set all the other bits to randomly (or pseudo-randomly) chosen // values. // UUID = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node // time-low = 4hexOctet // time-mid = 2hexOctet // time-high-and-version = 2hexOctet // clock-seq-and-reserved = hexOctet: // clock-seq-low = hexOctet // node = 6hexOctet // Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx // y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10 // y values are 8, 9, A, B var guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var hex = '0123456789abcdef'; var r = 0; var guidResponse = ""; for (var i = 0; i < 36; i++) { if (guidHolder[i] !== '-' && guidHolder[i] !== '4') { // each x and y needs to be random r = Math.random() * 16 | 0; } if (guidHolder[i] === 'x') { guidResponse += hex[r]; } else if (guidHolder[i] === 'y') { // clock-seq-and-reserved first hex is filtered and remaining hex values are random r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0?? r |= 0x8; // set pos 3 to 1 as 1??? guidResponse += hex[r]; } else { guidResponse += guidHolder[i]; } } return guidResponse; };