在开发中偶尔会遇到需要生成唯一id的时候,比如对数组的任意一项进行多次增删改,这时就需要给每一项添加唯一标识符来加以区分。
以下总结了几种生成唯一标识的方法,仅供参考。
1、通过地址的方式
function uuid(){
const tempUrl = URL.createObjectURL(new Blob());
const uuid = tempUrl.toString();
URL.revokeObjectURL(tempUrl); // 释放这个url
return uuid.substring(uuid.lastIndexOf("/") + 1)
}
console.log(uuid()) // 26dec868-b29f-42e5-9eb6-9c59396ae411
2、利用随机数结合16进制生成唯一值
function generateRandom() {
return Math.random().toString(16).slice(2);
}
// 45c3a3a294527
3、获取UUID标识请求
function guidGenerator() {
var S4 = function() {
return ((1 + Math.random())*0X10000|0).toString(16).substring(1);
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
console.log(guidGenerator(), '======这个是UUID随机数')
4、随机串串
function randomString(len) {
len = len || 32
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz1234567890'
var maxPos = chars.length
var pwd = ''
for (var i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos))
}
return pwd
}
randomString() // ShabfpZYnAMDErwd9yxPtNzRPBsfTXHz
5、生成标准的uuid,且方法最简单
function uuid() {
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);
});
}
console.log( uuid() ); // 12c96135-d4b6-488f-ba1d-449b27851e0b
6、5的拓展,生成标准的uuid,且使用了随机种子,比方法一要好
function uuid() {
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是随机种子
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
console.log( uuid() ) ; // 826fe4be-631c-4a63-83e9-96a788e8a569
7、生成了不太规范的唯一标识,但是平时使用是最简便的
var uuid = new Date().getTime() + Math.random().toString(36).substr(2);
console.log( uuid ); // 1590753224242oqgomgkv7tp
8、格式化时间的函数
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;
}
var uuid = formatDateTime() + Math.random().toString(36).substr(2);
console.log(uuid); // 20200529195844692wbkvn5l
9、uuid高级
function uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
console.log( uuid() ) ; // 337f459e-7d36-4cb4-838e-09f5fe7b3769
10、指定长度和基数
function uuid3(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
console.log( uuid3() ); // 2089EC65-DB7F-498D-910D-2B3F3BB585E8
11、生成NanoID的方法
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"
上面的方法仅供参考。还有很多很多类似的库,也可以直接使用,比如uuid,md5,nanoid 等等
添加好友备注【进阶学习】拉你进技术交流群