上一篇文章介绍了一种用雪花算法生成GUID的方法,下面介绍里外一种生成GUID并导出为.txt文件的方法:
话不多少 show you the code !
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>GUID</title> </head> <body> <button id="save" type="button">保存GUID文件</button> <script type="text/javascript"> var GUID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; var GUID_LENGTH = 20,res = []; var guid = function(a) { // 改变参数i,想要多少个给多少 for (var i = 0; i < 10; i++) { a = null != a ? a : GUID_LENGTH; for (var b = [], str = '', c = 0; c < a; c++) { b.push(GUID_ALPHABET.charAt(Math.floor(Math.random() * GUID_ALPHABET.length))); } str = b.join(""); console.log('str--' + i, str); res.push(str+'\n'); } return res; }; document.querySelector('#save').addEventListener('click', saveFile); function fakeClick(obj) { var ev = document.createEvent("MouseEvents"); ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); obj.dispatchEvent(ev); } function exportRaw(name, data) { var urlObject = window.URL || window.webkitURL || window; var export_blob = new Blob([data]); var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); save_link.href = urlObject.createObjectURL(export_blob); save_link.download = name; fakeClick(save_link); } function saveFile() { var inValue = guid(); exportRaw('guid.txt', inValue); } </script> </body> </html>
另外,如果想要使生成的GUID更复杂,更有序,可以在这个生成的GUID字符串基础上加 时间戳 或 相关的业务分类字符串 等等。
已经验证该方法生成的大量ID没有重复。