JS生成GUID方法


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;
        }
    }
}

使用方法:

var guid = new GUID();

alert(guid.newGUID());

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM