guid 生成

          全局唯一標識分區表(GUID Partition Table,縮寫:GPT)是指全局唯一標示磁盤分區表格式。它是可擴展固件接口(EFI)標準(被Intel用於替代個人計算機的BIOS)的一部分,被用於替代BIOS系統中的以32bits來存儲邏輯塊地址和大小信息的主引導記錄(MBR)分區表。

          GUID的格式爲:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

function GUID(){
    this.date = new Date();
  
    /* 判斷是否初始化過,如果初始化過以下代碼,則以下代碼將不再執行,實際中只執行一次 */
    if (typeof this.newGUID != 'function') {
      
      /* 生成GUID碼 */
      GUID.prototype.newGUID = function() {
        this.date = new Date();
        var guidStr = '';
          sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
          sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
        for (var i = 0; i < 9; i++) {
          guidStr += Math.floor(Math.random()*16).toString(16);
        }
        guidStr += sexadecimalDate;
        guidStr += sexadecimalTime;
        while(guidStr.length < 32) {
          guidStr += Math.floor(Math.random()*16).toString(16);
        }
        return this.formatGUID(guidStr);
      }
  
      /*
       * 功能:獲取當前日期的GUID格式,即8位數的日期:19700101
       * 返回值:返回GUID日期格式的字條串
       */
      GUID.prototype.getGUIDDate = function() {
        return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
      }
  
      /*
       * 功能:獲取當前時間的GUID格式,即8位數的時間,包括毫秒,毫秒爲2位數:12300933
       * 返回值:返回GUID日期格式的字條串
       */
      GUID.prototype.getGUIDTime = function() {
        return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero( parseInt(this.date.getMilliseconds() / 10 ));
      }
  
      /*
      * 功能: 爲一位數的正整數前面添加0,如果是可以轉成非NaN數字的字符串也可以實現
       * 參數: 參數表示準備再前面添加0的數字或可以轉換成數字的字符串
       * 返回值: 如果符合條件,返回添加0後的字條串類型,否則返回自身的字符串
       */
      GUID.prototype.addZero = function(num) {
        if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
          return '0' + Math.floor(num);
        } else {
          return num.toString();
        }
      }
  
      /* 
       * 功能:將y進制的數值,轉換爲x進制的數值
       * 參數:第1個參數表示欲轉換的數值;第2個參數表示欲轉換的進制;第3個參數可選,表示當前的進制數,如不寫則爲10
       * 返回值:返回轉換後的字符串
       */
      GUID.prototype.hexadecimal = function(num, x, y) {
        if (y != undefined) {
          return parseInt(num.toString(), y).toString(x);
        } else {
          return parseInt(num.toString()).toString(x);
        }
      }
  
      /*
       * 功能:格式化32位的字符串爲GUID模式的字符串
       * 參數:第1個參數表示32位的字符串
       * 返回值:標準GUID格式的字符串
       */
      GUID.prototype.formatGUID = function(guidStr) {
        var str1 = guidStr.slice(0, 8) + '-',
          str2 = guidStr.slice(8, 12) + '-',
          str3 = guidStr.slice(12, 16) + '-',
          str4 = guidStr.slice(16, 20) + '-',
          str5 = guidStr.slice(20);
        return str1 + str2 + str3 + str4 + str5;
      }
    }
  }

調用方法

let guid = new GUID();  
console.log('guid:',guid.newGUID()); 

 這就ok了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章