使用Javascript时间创建唯一数字

137

我需要使用JavaScript动态生成唯一的ID号码。过去,我是通过使用时间来创建一个数字来实现这一点的。该数字由四位数年份、两位数月份、两位数日期、两位数小时、两位数分钟、两位数秒和三位数毫秒组成。因此它看起来像这样:20111104103912732... 这足以提供我所需的唯一数字的确定性。

已经有一段时间了,我没有这个代码了。是否有人可以提供这个代码,或者有更好的建议来生成唯一ID?


5
可能是如何在Javascript中创建GUID / UUID?的重复问题。 - August Lilleaas
你考虑过使用 new Date().toISOString() 吗? - Anna B
39个回答

0

使用JavaScript时间V2.0生成唯一数字

JavaScript时间值:自1970年01月01日以来的毫秒数
100%保证生成不同的数字...

let Q = {};
Q.in = document.querySelector('#in');
Q.info = document.querySelector('#butStart');
Q.copy = document.querySelector('#butCopy');
Q.demo = document.querySelector('#demo');

function genUniqueNum() {
    let kol = Q.in.value,
        data, tmp, out = '';
    let i = 0;

    while (i < kol) {
        data = new Date().getTime();
        if (data != tmp) {
            out += `${data}\n`;
            tmp = data;
            i++;
        }
    }
    Q.demo.value += out;
}

function elemTarget(e) {
    e = e || window.event;
    e.preventDefault();
    return e.target;
}

document.addEventListener('click', (e) => {
    let elem = elemTarget(e);

    if (elem.id === 'butStart') {
        genUniqueNum();
    }
    if (elem.id === 'butCopy' && Q.demo.value) {
        Q.demo.select();
        Q.demo.setSelectionRange(0, 99999);
        document.execCommand("copy");
    }
    if (elem.id === 'butClear') {
        Q.demo.value = '';
    }
});
#in{
  width: 91px;
}

#butStart,
#butCopy,
#butClear {
  width: 100px;
  margin: 3px 2px 0px 0;
  height: 25px;
}

#butCopy {
  margin: 0 5px;
}

#demo {
  width: 200px;
  height: 100px;
  margin: 5px 0 0;
}
  <input type="number" id="in" maxlength="1000000" minlength="1" value="5">
  <label> - Amount</label><br>
  <button id="butStart">Start</button><br>
  <textarea id="demo"></textarea><br>
  <button id="butClear">Clear</button><button id="butCopy">Copy</button>

Fork-codepen.io


0

function createUniqueId() {
  var date = new Date().getTime();
  var uniqueId = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
    /[xy]/g,
    function (c) {
      var r = (date + Math.random() * 16) % 16 | 0;
      date = Math.floor(date / 16);
      return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
    }
  );
  return uniqueId;
}

console.log(createUniqueId());


0
我已经用这种方式完成了。
function uniqeId() {
   var ranDom = Math.floor(new Date().valueOf() * Math.random())
   return _.uniqueId(ranDom);
}

0
function getUniqueNumber() {

    function shuffle(str) {
        var a = str.split("");
        var n = a.length;
        for(var i = n - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
        return a.join("");
    }
    var str = new Date().getTime() + (Math.random()*999 +1000).toFixed() //string
    return Number.parseInt(shuffle(str));   
}

0

关于 #Marcelo Lazaroni 上面的解决方案

Date.now() + Math.random()

返回一个数字,例如1567507511939.4558(限制为4位小数),并且每0.1%会产生非唯一的数字(或冲突)。

添加toString()可以解决此问题

Date.now() + Math.random().toString()

返回字符串“15675096840820.04510962122198503”,而且速度非常慢,以至于您永远不会得到“相同”的毫秒数。


0

获取唯一的数字:

function getUnique(){
    return new Date().getTime().toString() + window.crypto.getRandomValues(new Uint32Array(1))[0];
}
// or 
function getUniqueNumber(){
    const now = new Date();
    return Number([
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        now.getHours(),
        now.getMinutes(),
        now.getUTCMilliseconds(),
        window.crypto.getRandomValues(new Uint8Array(1))[0]
    ].join(""));
}

例子:

getUnique()
"15951973277543340653840"

for (let i=0; i<5; i++){
    console.log( getUnique() );
}
15951974746301197061197
15951974746301600673248
15951974746302690320798
15951974746313778184640
1595197474631922766030

getUniqueNumber()
20206201121832230

for (let i=0; i<5; i++){
    console.log( getUniqueNumber() );
}
2020620112149367
2020620112149336
20206201121493240
20206201121493150
20206201121494200

您可以使用以下方式更改长度:

new Uint8Array(1)[0]
// or
new Uint16Array(1)[0]
// or
new Uint32Array(1)[0]

问题要求一个唯一的数字,而不是随机字符串。 - tshimkus

0
使用toString(36)有点慢,以下是更快且独特的解决方案:
new Date().getUTCMilliseconds().toString() +
"-" +
Date.now() +
"-" +
filename.replace(/\s+/g, "-").toLowerCase()

0

使用 Math.random() 的人并不是真正的随机,因为它是一个伪随机生成器。

我刚刚发现了这个,它要好得多。我建议使用服务器 NodeJS 解决方案(而不是使用浏览器)。

// Exists at least Nodejs 16.x.x and above. globalThis.crypto.randomInt is better, more random and support negative range
function randomNumber(min: number, max: number) {
  return globalThis.crypto.randomInt(min, max);
}

https://www.geeksforgeeks.org/node-js-crypto-randomint-method/ 之所以使用globalthis.,是因为我在NodeJS中使用它。


-4

只需编写使用自增的代码

i=1;
getUnique(){
return i++
}

但是如果我在其他地方再次执行 i=1,这个方法就不再起作用了,对吗? - General Grievance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接