记录下JS生成唯一id的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var uuid = formatDateTime() + Math.random().toString(36).substr(2); function formatDateTime() { var date = new Date(); var y = date.getFullYear(); var m = date.getMonth() + 1; m = m < 10 ? ('0' + m) : m; var d = date.getDate(); d = d < 10 ? ('0' + d) : d; var h = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); return y + m + d + h + minute + second; } console.log(uuid) // 20190212142639jreyv1t83yd |
1 2 3 4 5 6 7 8 9 10 11 12 13 | function generateUUID() { var d = new Date().getTime(); if (window.performance && typeof window.performance.now === "function") { d += performance.now(); //use high-precision timer if available } var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; } console.log( generateUUID() ) // f0ed305c-ec19-4967-b323-eef07a4cf2d8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | let urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' let nanoid = (size = 21) => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. let i = size while (i--) { // `| 0` is more compact and faster than `Math.floor()`. id += urlAlphabet[(Math.random() * 64) | 0] } return id } nanoid() // "AfRTJv9hRo42vKKUDBQLX" |
谷歌v92版本后,已经支持原生方法crypto.randomUUID(),真香,不过暂时浏览器兼容性较差,在若干年未来的你看到这里,不妨试试
1 2 | consle.log(crypto.randomUUID()) // '2b6d301f-07f9-42b1-b69c-ab2b4e13ef1a' |
上一篇:jquery中innerWidth(),outerWidth(),outerWidth(true)和width()的区别
下一篇:Vue scoped CSS 与深度作用选择器 deep
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Javascript生成唯一id标识符(GUID,UUID,ID)的方法"
最新评论