UUID 是指Universally Unique Identifier,翻译为中文是通用唯一识别码,今天小编就来聊一聊关于生成uuid的方式有几种?接下来我们就一起去研究一下吧!

生成uuid的方式有几种(js生成UUID)

生成uuid的方式有几种

UUID 是指Universally Unique Identifier,翻译为中文是通用唯一识别码

编码规则

UUID(Universally Unique Identifier)全局唯一标识符,定义为一个字符串主键,采用32位数字组成,编码采用16进制,定义了在时间和空间都完全惟一的系统信息。

UUID的编码规则:

1)1~8位采用系统时间,在系统时间上精确到毫秒级保证时间上的惟一性;2)9~16位采用底层的IP地址,在服务器集群中的惟一性;3)17~24位采用当前对象的HashCode值,在一个内部对象上的惟一性;4)25~32位采用调用方法的一个随机数,在一个对象内的毫秒级的惟一性。通过以上4种策略可以保证惟一性。在系统中需要用到随机数的地方都可以考虑采用UUID算法。

上代码

const hexList = []; for (let i = 0; i <= 15; i ) { hexList[i] = i.toString(16); } function buildUUID() { let uuid = ""; for (let i = 1; i <= 36; i ) { if (i === 9 || i === 14 || i === 19 || i === 24) { uuid = "-"; } else if (i === 15) { uuid = 4; } else if (i === 20) { uuid = hexList[(Math.random() * 4) | 8]; } else { uuid = hexList[(Math.random() * 16) | 0]; } } return uuid.replace(/-/g, ""); } let unique = 0; function buildShortUUID(prefix = "") { const time = Date.now(); const random = Math.floor(Math.random() * 1000000000); unique ; return prefix "_" random unique String(time); } console.log(buildUUID()); // 1a8ba5edde0542a18b06304b1bed5d7c console.log(buildShortUUID("test")); // test_43581603011638886158139

,