在 JavaScript 中创建全局唯一 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12223529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:26:05  来源:igfitidea点击:

Create Globally Unique ID in JavaScript

javascript

提问by Trevor Norris

I have a script that, when a user loads, creates a unique id. Which is then saved in localStorageand used for tracking transactions. Sort of like using a cookie, except since the browser is generating the unique id there might be collisions when sent to the server. Right now I'm using the following code:

我有一个脚本,当用户加载时,它会创建一个唯一的 ID。然后将其保存localStorage并用于跟踪交易。有点像使用 cookie,除了因为浏览器正在生成唯一的 id,所以在发送到服务器时可能会发生冲突。现在我正在使用以下代码:

function genID() {
    return Math.random().toString(36).substr(2)
        + Math.random().toString(36).substr(2)
        + Math.random().toString(36).substr(2)
        + Math.random().toString(36).substr(2);
}

I realize this is a super basic implementation, and want some feedback on better ways to create a "more random" id that will prevent collisions on the server. Any ideas?

我意识到这是一个超级基本的实现,并且想要一些关于创建“更随机”的 id 的更好方法的反馈,以防止服务器上的冲突。有任何想法吗?

采纳答案by James South

I've used this in the past. Collision odds should be very low.

我过去用过这个。碰撞几率应该非常低。

var generateUid = function (separator) {
    /// <summary>
    ///    Creates a unique id for identification purposes.
    /// </summary>
    /// <param name="separator" type="String" optional="true">
    /// The optional separator for grouping the generated segmants: default "-".    
    /// </param>

    var delim = separator || "-";

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

    return (S4() + S4() + delim + S4() + delim + S4() + delim + S4() + delim + S4() + S4() + S4());
};