js生成前端唯一id,比如uuid
简单的生成:
虽然此方法简单但是大批量生成会有重复...,但是性能好。
function guid() { return Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36); }
复杂的生成:
可以利用时间戳,目前亲测同时10W条没有重复。
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; } let arr = []; for(i = 0; i< 1000; i++) { var guids = formatDateTime() + Math.random().toString(36).substr(2); if (arr.indexOf(guids) > -1){ console.log(guids, arr.indexOf(guids)) }; arr.push(guids); };
模拟UUID生成方式:
目前亲测同时10W条没有重复
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; } let arr = []; for(i = 0; i< 1000; i++) { var guids = formatDateTime() + Math.random().toString(36).substr(2); if (arr.indexOf(guids) > -1){ console.log(guids, arr.indexOf(guids)) }; arr.push(guids); };