javascript 实现生成GUID / UUID的多种方法

GUID(全局唯一标识符)或(UUID)通用唯一标识符是一个 16 字节的二进制值,是旨在提供某些唯一性保证的标识符。

Math.Random

Javascript 中使用 Math.Random() 生成 GUID

 uuidv4: function () {
    return '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);
      }
    );
  },

由于上面创建的 GUID 高度依赖Math.Random(),可以创建 GUID 的简单写法,但不能将其视为高质量的随机数生成器。因此,该方法的GUID 可能会发生冲突,但可以用于少量生成。

优化方案:加入日期和时间,确保它是唯一的。

generateUUIDUsingMathRandom: function () {
   var d = new Date().getTime(); //Timestamp
   var d2 =
     (performance && performance.now && performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
     /[xy]/g,
     function (c) {
       var r = Math.random() * 16; //random number between 0 and 16
       if (d > 0) {
         //Use timestamp until depleted
         r = (d + r) % 16 | 0;
         d = Math.floor(d / 16);
       } else {
         //Use microseconds since page-load if supported
         r = (d2 + r) % 16 | 0;
         d2 = Math.floor(d2 / 16);
       }
       return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
     }
   );
 },

Crypto API

Crypto接口提供当前上下文中可用的基本加密功能。它允许访问加密的强随机数生成器和加密原语。

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

Pseudo-Random Number

使用伪随机数

PseudoUUID: function () {
      var s = [];
      var hexDigits = '0123456789abcdef';
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-';
      var uuid = s.join('');
      return uuid;
    },

基于Vue Cli 2.0 模板示例如下:
在这里插入图片描述
App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="https://vuejs.org/images/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import Crypto from 'crypto';

export default {
  name: 'App',
  components: {
    HelloWorld,
  },
  mounted() {
    this.init();
  },
  methods: {
    init: function () {
      const uuid_1 = this.uuidv4();
      console.log(uuid_1); // 5b3e9636-88ec-4dd7-8ba2-a8e511a36139
      const uuid_2 = this.generateUUIDUsingMathRandom();
      console.log(uuid_2); // 41a605ef-1dff-4a69-bece-342104892733
      const uuid_3 = this.cryptoUuidv4();
      console.log(uuid_3); // 8db33e79-0a18-4563-95a0-e1b13ba80f68
      const uuid_4 = this.PseudoUUID();
      console.log(uuid_4); // 20e44d2b-2e96-4eb1-b457-7d274a497468
    },

    //1: Math.random Simple
    uuidv4: function () {
      return '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);
        }
      );
    },

    //2: Math.random High
    generateUUIDUsingMathRandom: function () {
      var d = new Date().getTime(); //Timestamp
      var d2 =
        (performance && performance.now && performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
        /[xy]/g,
        function (c) {
          var r = Math.random() * 16; //random number between 0 and 16
          if (d > 0) {
            //Use timestamp until depleted
            r = (d + r) % 16 | 0;
            d = Math.floor(d / 16);
          } else {
            //Use microseconds since page-load if supported
            r = (d2 + r) % 16 | 0;
            d2 = Math.floor(d2 / 16);
          }
          return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
        }
      );
    },

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

    //4. Pseudo-Random Number
    PseudoUUID: function () {
      var s = [];
      var hexDigits = '0123456789abcdef';
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-';
      var uuid = s.join('');
      return uuid;
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值