首页 / 问答 / JavaScript(js)中如何快速生成随机GUID/UUID字符串呢?

JavaScript(js)中如何快速生成随机GUID/UUID字符串呢?

0

无论在后端开发还是在前端开发中,都会遇到随机生成数字,字符串等需求,比如,在.NET中,要生成一个GUID随机字符串,则可以调用方法Guid.NewGuid()
当前,有需求用JavaScript创建全局唯一的字符串,并且要在所有主流浏览器上可用,生成的GUID/UUID应该至少是32个字符,并且应该保持在ASCII范围内,以避免在传递它们时遇到麻烦。

要完成这样的需求,使用JavaScript(js)应该如何快速生成随机GUID/UUID字符串呢?

回复 [×]
提交评论
请输入评论内容

7 个回答

  • 0

    在JavaScript(js)中,可以使用crypto.getRandomValues()函数封装一个生成GUID/UUID随机字符串的函数,如下:

    function uuidv4() {
      return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
      );
    }
    

    调用示例:

    console.log(uuidv4());
    
    Rector的个人主页

    Rector

    2021-11-06 回答

    • 0

      或者,使用Math.random()封装一个生成GUID/UUID随机字符串的函数,如下:

      function generateUUID() {
          var d = new Date().getTime();
          var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now()*1000)) || 0;
          return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
              var r = Math.random() * 16;
              if(d > 0){
                  r = (d + r)%16 | 0;
                  d = Math.floor(d/16);
              } else {
                  r = (d2 + r)%16 | 0;
                  d2 = Math.floor(d2/16);
              }
              return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
          });
      }
      

      调用示例:

      console.log(generateUUID());
      
      Rector的个人主页

      Rector

      2021-11-06 回答

      • 0

        下面是一个进过优化的,高效的生成GUID/UUID随机字符串的函数:

        var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
        function generateUUID()
        {
            var d0 = Math.random()*0xffffffff|0;
            var d1 = Math.random()*0xffffffff|0;
            var d2 = Math.random()*0xffffffff|0;
            var d3 = Math.random()*0xffffffff|0;
            return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
            lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
            lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
            lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
        }
        
        console.log(generateUUID())
        
        Rector的个人主页

        Rector

        2021-11-06 回答

        • 0

          或者,还可以是下面的生成GUID/UUID随机字符串的函数:

          function generateGuid() {
            var result, i, j;
            result = '';
            for(j=0; j<32; j++) {
              if( j == 8 || j == 12 || j == 16 || j == 20)
                result = result + '-';
              i = Math.floor(Math.random()*16).toString(16).toUpperCase();
              result = result + i;
            }
            return result;
          }
          
          Rector的个人主页

          Rector

          2021-11-06 回答

          • 0
            var uuid = function() {
                var buf = new Uint32Array(4);
                window.crypto.getRandomValues(buf);
                var idx = -1;
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                    idx++;
                    var r = (buf[idx>>3] >> ((idx%8)*4))&15;
                    var v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
            };
            
            Rector的个人主页

            Rector

            2021-11-06 回答

            • 0
              function uuid()
              {
                 var chars = '0123456789abcdef'.split('');
              
                 var uuid = [], rnd = Math.random, r;
                 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                 uuid[14] = '4'; // version 4
              
                 for (var i = 0; i < 36; i++)
                 {
                    if (!uuid[i])
                    {
                       r = 0 | rnd()*16;
              
                       uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
                    }
                 }
              
                 return uuid.join('');
              }
              
              Rector的个人主页

              Rector

              2021-11-06 回答

              • 0

                以下是GUID对象方式的实现:

                var crypto = window.crypto || window.msCrypto || null; // IE11 fix
                
                var Guid = Guid || (function() {
                
                  var EMPTY = '00000000-0000-0000-0000-000000000000';
                
                  var _padLeft = function(paddingString, width, replacementChar) {
                    return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
                  };
                
                  var _s4 = function(number) {
                    var hexadecimalResult = number.toString(16);
                    return _padLeft(hexadecimalResult, 4, '0');
                  };
                
                  var _cryptoGuid = function() {
                    var buffer = new window.Uint16Array(8);
                    window.crypto.getRandomValues(buffer);
                    return [_s4(buffer[0]) + _s4(buffer[1]), _s4(buffer[2]), _s4(buffer[3]), _s4(buffer[4]), _s4(buffer[5]) + _s4(buffer[6]) + _s4(buffer[7])].join('-');
                  };
                
                  var _guid = function() {
                    var currentDateMilliseconds = new Date().getTime();
                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(currentChar) {
                      var randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0;
                      currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16);
                      return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16);
                    });
                  };
                
                  var create = function() {
                    var hasCrypto = crypto != 'undefined' && crypto !== null,
                      hasRandomValues = typeof(window.crypto.getRandomValues) != 'undefined';
                    return (hasCrypto && hasRandomValues) ? _cryptoGuid() : _guid();
                  };
                
                  return {
                    newGuid: create,
                    empty: EMPTY
                  };
                })();
                
                // 调用示例
                console.log(Guid.newGuid()); // c6c2d12f-d76b-5739-e551-07e6de5b0807
                console.log(Guid.empty()); // 00000000-0000-0000-0000-000000000000
                
                Rector的个人主页

                Rector

                2021-11-06 回答

                我来回答