UUID

UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写,是一种软件建构的标准,亦为开放软件基金会组织在分布式计算环境领域的一部分。

使用 Math.random()

  [js]
1
2
3
4
5
6
7
function getUuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); }

使用crypto提供的randomUUID方法

  [js]
1
const UUID = crypto.randomUUID();

使用crypto提供的getRandomValues方法

  [js]
1
2
3
function getUuid() { return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)); }

实际开发中推荐的方法

  [js]
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
function getUuid () { if (typeof crypto === 'object') { if (typeof crypto.randomUUID === 'function') { return crypto.randomUUID(); } if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') { const callback = (c) => { const num = Number(c); return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16); }; return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, callback); } } let timestamp = new Date().getTime(); let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { let random = Math.random() * 16; if (timestamp > 0) { random = (timestamp + random) % 16 | 0; timestamp = Math.floor(timestamp / 16); } else { random = (perforNow + random) % 16 | 0; perforNow = Math.floor(perforNow / 16); } return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16); }); };

小结

经常整理归纳。

如何把这个 js 文件放在 CDN 上?

参考资料

https://juejin.cn/post/7066608015784280072