• js生成唯一的uuid


    ---恢复内容开始---

    在做项目的时候出现这样的一种情况,需要动态生成唯一的uuid,刚开始我的思路是这样的,我可以根据时间来做,然后出现了下面的思路:

    var uuid = "cms"+mydate.getDay()+ mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds();//根据时间来自动生成uuid,保证生成的id是唯一的

    然后呢,我用for循环,发现生成的uuid是一致的,如下图所示:

    也就是说生成的id是一样的,这样明显不符合我的要求,然后就搜索更好的生成uuid的方法,然后有了两种

    1,在我上面的方法的基础上加上一个随机数,这样可以生成uuid,即,在原来的基础上加上随机数

    var uuid = "cms"+mydate.getDay()+ mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds()+ Math.round(Math.random() * 10000);

    生成的结果如下:没有冲突

     

    但是呢,最好的方法是自己生成uuid,可以用下面的额方法

    方法2,

        //用于生成uuid
        function S4() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        function guid() {
            return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
        }

    具体的调用方法:

    var uuid = "cms"+guid();

    调用的结果如下:

  • 相关阅读:
    hdu 1542 Atlantis
    cf C. Cupboard and Balloons
    cf C. Tourist Problem
    hdu 4027 Can you answer these queries?
    hdu 1255 覆盖的面积
    hdu 1698 Just a Hook
    zoj 1610 Count the Colors
    hdu 4302 Holedox Eating
    hdu 4288 Coder
    tsne理论学习
  • 原文地址:https://www.cnblogs.com/ningheshutong/p/6559848.html
Copyright © 2020-2023  润新知