如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。

我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。


当前回答

原始 URL.createObjectURL 正在产生 UUID. 您可以利用此。

function uuid() {
  const url = URL.createObjectURL(new Blob())
  const [id] = url.toString().split('/').reverse()
  URL.revokeObjectURL(url)
  return id
}

其他回答

这里是一个方法,使用真实的随机通过 random.org 生成 RFC4122 如果错误,它会回到浏览器的内置加密图书馆,这应该几乎是相同的好。

async function UUID() {
    //get 31 random hex characters
    return (await (async () => {
        let output;
        try {
            //try from random.org
            output = (await (
                await fetch('https://www.random.org/integers/?num=31&min=0&max=15&col=31&base=16&format=plain&rnd=new')
            ).text())
                //get rid of whitespace
                .replace(/[^0-9a-fA-F]+/g, '')
            ;
            if (output.length != 31)
                throw '';
        }
        catch {
            output = '';
            try {
                //failing that, try getting 16 8-bit digits from crypto
                for (let num of crypto.getRandomValues(new Uint8Array(16)))
                    //interpret as 32 4-bit hex numbers
                    output += (num >> 4).toString(16) + (num & 15).toString(16);
                //we only want 31
                output = output.substr(1);
            }
            catch {
                //failing THAT, use Math.random
                while (output.length < 31)
                    output += (0 | Math.random() * 16).toString(16);
            }
        }
        return output;
    })())
        //split into appropriate sections, and set the 15th character to 4
        .replace(/^(.{8})(.{4})(.{3})(.{4})/, '$1-$2-4$3-$4-')
        //force character 20 to the correct range
        .replace(/(?<=-)[^89abAB](?=[^-]+-[^-]+$)/, (num) => (
            (parseInt(num, 16) % 4 + 8).toString(16)
        ))
    ;
}

此分類上一篇

我想了解布罗法的答案,所以我扩展了它并添加了评论:

var uuid = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
        /[xy]/g,
        function (match) {
            /*
            * Create a random nibble. The two clever bits of this code:
            *
            * - Bitwise operations will truncate floating point numbers
            * - For a bitwise OR of any x, x | 0 = x
            *
            * So:
            *
            * Math.random * 16
            *
            * creates a random floating point number
            * between 0 (inclusive) and 16 (exclusive) and
            *
            * | 0
            *
            * truncates the floating point number into an integer.
            */
            var randomNibble = Math.random() * 16 | 0;

            /*
            * Resolves the variant field. If the variant field (delineated
            * as y in the initial string) is matched, the nibble must
            * match the mask (where x is a do-not-care bit):
            *
            * 10xx
            *
            * This is achieved by performing the following operations in
            * sequence (where x is an intermediate result):
            *
            * - x & 0x3, which is equivalent to x % 3
            * - x | 0x8, which is equivalent to x + 8
            *
            * This results in a nibble between 8 inclusive and 11 exclusive,
            * (or 1000 and 1011 in binary), all of which satisfy the variant
            * field mask above.
            */
            var nibble = (match == 'y') ?
                (randomNibble & 0x3 | 0x8) :
                randomNibble;

            /*
            * Ensure the nibble integer is encoded as base 16 (hexadecimal).
            */
            return nibble.toString(16);
        }
    );
};

最好的方式:

function(
  a, b               // Placeholders
){
  for(               // Loop :)
      b = a = '';    // b - result , a - numeric variable
      a++ < 36;      //
      b += a*51&52   // If "a" is not 9 or 14 or 19 or 24
                  ?  //  return a random number or 4
           (
               a^15              // If "a" is not 15,
                  ?              // generate a random number from 0 to 15
               8^Math.random() *
               (a^20 ? 16 : 4)   // unless "a" is 20, in which case a random number from 8 to 11,
                  :
               4                 //  otherwise 4
           ).toString(16)
                  :
         '-'                     //  In other cases, (if "a" is 9,14,19,24) insert "-"
      );
  return b
 }

最小化:

function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b}

ES6 样品

const guid=()=> {
  const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);     
  return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}

对于那些在Windows上使用JavaScript的人(例如,Windows Script Host(WSH),CScript,和HTA)。一个可以使用ActiveX。

WScript.Echo((new ActiveXObject("Scriptlet.TypeLib")).Guid)

请注意,这个答案仅适用于我列出的技术,它不会在任何浏览器中工作,甚至不是Microsoft Edge! 因此,你的距离与这个答案不同。