GUID(全域唯一標識符)是指在一台機器上生成的數字,它保證在同一時空中的所有機器都是唯一的。平台通常會提供生成 GUID 的 API,其算法用到了以太網卡位址、奈秒級時間、晶片 ID 碼和許多可能的數字,唯一的缺陷是生成的結果字串較長。
GUID 的格式為:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
雖然 GUID 在前端開發中用處不大,但當需要插入某個與後台對應的 ID 時,自行生成一個會方便許多。由於前端難以取得網卡位址、奈秒級時間等資訊,我們可以採用模擬方式實現:
function GUID() { this.date = new Date(); if (typeof this.newGUID != 'function') { 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.prototype.getGUIDDate = function() { return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay()); } 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 )); } GUID.prototype.addZero = function(num) { if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) { return '0' + Math.floor(num); } else { return num.toString(); } } GUID.prototype.hexadecimal = function(num, x, y) { if (y != undefined) { return parseInt(num.toString(), y).toString(x); } else { return parseInt(num.toString()).toString(x); } } 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; } } }
GUID 物件
只需將其保存在一個 JS 檔案中並引用即可,然後呼叫:
var guid = new GUID(); alert(guid.newGUID());
其實現原理是採用系統時間與 18 位以上的十六進制隨機數組合,並將系統時間轉換為十六進制。這樣雖然仍有重複可能,但機率極低,可忽略不計。