Js 生成Guid
使用方法:
1、? 生成一個新GUID:var guid = Guid.NewGuid();
2、? 生成一個所有值均為0的GUID:
a)???????? var guid = new Guid();
b)???????? var guid = Guid.Empty;
3、? 比較兩個GUID是否相等:g1.Equals(g2);
4、? 獲取Guid的字符串形式。其中, format為String類型的可選參數,其含義為:
a)???????? “N”: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
b)???????? “D”? 由連字符分隔的 32 位數字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
c)???????? “B”? 括在大括號中、由連字符分隔的 32 位數字:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
d)???????? “P”? 括在圓括號中、由連字符分隔的 32 位數字:(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
?
代碼如下:
//表示全局唯一標識符 (GUID)。function Guid(g){var arr = new Array(); //存放32位數值的數組if (typeof(g) == "string"){ //如果構造函數的參數為字符串InitByString(arr, g);}else{InitByOther(arr);}//返回一個值,該值指示 Guid 的兩個實例是否表示同一個值。this.Equals = function(o){if (o && o.IsGuid){return this.ToString() == o.ToString();}else{return false;}}//Guid對象的標記this.IsGuid = function(){}//返回 Guid 類的此實例值的 String 表示形式。this.ToString = function(format){if(typeof(format) == "string"){if (format == "N" || format == "D" || format == "B" || format == "P"){return ToStringWithFormat(arr, format);}else{return ToStringWithFormat(arr, "D");}}else{return ToStringWithFormat(arr, "D");}}//由字符串加載function InitByString(arr, g){g = g.replace(/\{|\(|\)|\}|-/g, "");g = g.toLowerCase();if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1){InitByOther(arr);}else{for (var i = 0; i < g.length; i++){arr.push(g[i]);}}}//由其他類型加載function InitByOther(arr){var i = 32;while(i--){arr.push("0");}}/*根據所提供的格式說明符,返回此 Guid 實例值的 String 表示形式。N 32 位: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxD 由連字符分隔的 32 位數字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx B 括在大括號中、由連字符分隔的 32 位數字:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} P 括在圓括號中、由連字符分隔的 32 位數字:(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) */function ToStringWithFormat(arr, format){switch(format){case "N":return arr.toString().replace(/,/g, "");case "D":var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20,32);str = str.replace(/,/g, "");return str;case "B":var str = ToStringWithFormat(arr, "D");str = "{" + str + "}";return str;case "P":var str = ToStringWithFormat(arr, "D");str = "(" + str + ")";return str;default:return new Guid();}}}//Guid 類的默認實例,其值保證均為零。Guid.Empty = new Guid();//初始化 Guid 類的一個新實例。Guid.NewGuid = function(){var g = "";var i = 32;while(i--){g += Math.floor(Math.random()*16.0).toString(16);}return new Guid(g);}?
轉載于:https://www.cnblogs.com/aixinjueluogu/archive/2012/09/20/2694648.html
總結
- 上一篇: 第十八章 4string 字符串的合并
- 下一篇: Sharepoint学习笔记—Site