GUID(全局统一标识符)是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台会提供生成GUID的API。生成算法很有意思,用到了以太网卡地址、纳秒级时间、芯片ID码和许多可能的数字。GUID的唯一缺陷在于生成的结果串会比较大。
GUID的格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
大家都知道GUID在前端开发中用处不大,但如果需要插入某个ID,并且这个ID与后台对应等其它需要GUID的操作时,为了方便,我们还是可以生成一个GUID的。
一般在sql、java、C#等后台或数据库语言中生成GUID都很简单,而前端没有直接生成GUID的方法,只能自己手写一个。但由于GUID需要获取以太网卡的地址、以及纳秒级的时间等数字。而前端获取到这些信息比较困难(知道的童鞋请一定告诉我),而我们可以模拟实现生成GUID,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
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; } } }
|
只需要将其保存在一个JS文件中并引用即可。
然后我们只需要如下即可获取GUID码。
1 2
| var guid = new GUID(); alert(guid.newGUID());
|
实现原理很简单,这里只是采用了系统时间与18个以上的十六进制随机数组成,并用系统时间转换为十六进制,这样虽然还是有可能重复,但是重复的概率极低,可忽略不计。
以上为本人写的生成GUID的方法,如有更好的方法可以告诉我,谢谢!
最后更新时间:
这里可以写作者留言,标签和 hexo 中所有变量及辅助函数等均可调用,示例:
https://blog.afacat.com/2014/09/04/原生JavaScript生成GUID/