在 JavaScript 中生成 UUID 时发生冲突

编程入门 行业动态 更新时间:2024-10-28 14:30:25
本文介绍了在 JavaScript 中生成 UUID 时发生冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这与这个问题有关.我正在使用 这个答案 在 JavaScript 中生成 UUID:

This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); });

此解决方案似乎工作正常,但我遇到了冲突.这是我所拥有的:

This solution appeared to be working fine, but I am getting collisions. Here's what I have:

  • 在 Google Chrome 中运行的网络应用程序.
  • 16 个用户.
  • 这些用户在过去两个月中生成了大约 4000 个 UUID.
  • 我遇到了大约 20 次冲突 - 例如,今天生成的新 UUID 与大约两个月前相同(不同的用户).

是什么导致了这个问题,我该如何避免?

What is causing this issue and how can I avoid it?

推荐答案

我最好的猜测是 Math.random() 由于某种原因(听起来很奇怪)在您的系统上损坏了.这是我第一次看到有人发生碰撞的报告.

My best guess is that Math.random() is broken on your system for some reason (bizarre as that sounds). This is the first report I've seen of anyone getting collisions.

node-uuid 有一个 测试工具,你可以用于测试该代码中十六进制数字的分布.如果这看起来没问题,那么它不是 Math.random(),然后尝试将您正在使用的 UUID 实现替换为 uuid() 方法,然后查看如果你仍然得到好的结果.

node-uuid has a test harness that you can use to test the distribution of hex digits in that code. If that looks okay then it's not Math.random(), so then try substituting the UUID implementation you're using into the uuid() method there and see if you still get good results.

[更新:刚刚看到 Veselin 的报告关于 Math.random() 的错误在启动时.由于问题仅出现在启动时,node-uuid 测试不太可能有用.我将在 devoluk 链接上进行更详细的评论.]

[Update: Just saw Veselin's report about the bug with Math.random() at startup. Since the problem is only at startup, the node-uuid test is unlikely to be useful. I'll comment in more detail on the devoluk link.]

更多推荐

在 JavaScript 中生成 UUID 时发生冲突

本文发布于:2023-10-22 09:25:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1517114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发生冲突   JavaScript   UUID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!