我有两个数据对象,即用户和记录。
用户应该有一个唯一的ID,记录也应该有一个。该记录具有所有者,用户,每条记录包含userId。所以我创建了一个简单的Id生成器
$( document ).ready(function() {
$("#btn").click(function(){
createId();
});
});
var myIds = [];
function createId(){ // Create new ID and push it to the ID collection
var id = generateNewId();
myIds.push(id);
console.log("The current id is: ");
console.log(id);
console.log("The array contains: ");
console.log(myIds);
}
function generateNewId(){ // Check for existing IDs
var newId = getNewId();
if($.inArray(newId, myIds) > -1){ // Does it already exist?
newId = generateNewId(); //
}
else{
return newId;
}
}
function getNewId(){ // ID generator
var possibleChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var serialLength = 20;
var generatedId = '';
for (var i = 0; i < serialLength; i++) {
var randomNumber = Math.floor(Math.random() * possibleChars.length);
generatedId += possibleChars.substring(randomNumber, randomNumber + 1);
}
return generatedId;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Add new ID</button>
&#13;
所以这个发生器适用于两个ID。但是生成用户ID的正确方法是什么?
在国家/地区创建帐户时,有没有办法生成唯一的用户ID?当时 ?用户?
记录对象也有一个ID,有没有办法让它包含其所有者的部分,用户ID?
显示的生成器能够创建大量可能的ID。但是,当没有可能性时会发生什么?这就是为什么我想要一个更好的&#34;创建ID的方法。
答案 0 :(得分:2)
如果您正在使用节点,则可以使用uuid:https://www.npmjs.com/package/uuid 此程序包允许您创建通用唯一ID。
在浏览器方面,最好的办法是实现一项简单的功能,完成工作。你的不错,但你冒险碰撞。我会使用来自npm uuidv4的那个更进化的那个:
function uuidv4() {
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);
});
}
const uuidv4es8 = () =>
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
});
//EDIT customize it if you want:
const uuidv4es8WithoutDash = () =>
'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
});
const uuidFactory =
(myFormat,encodingBase) =>
() =>
myFormat.replace(/[a-zA-Z]/g, c => (Math.random() * encodingBase| 0).toString(encodingBase))
console.log(uuidv4())
console.log(uuidv4())
console.log(uuidv4())
console.log(uuidv4())
console.log(uuidv4())
console.log(uuidv4es8())
//EDIT: delete the dash if you want !
console.log(uuidv4es8WithoutDash())
//Create a function that returns uuid as you want them:
let myUuidv4es8 = uuidFactory('1-xxxxx-xxxxx',23)
console.log(myUuidv4es8())
console.log(myUuidv4es8())
myUuidv4es8 = uuidFactory('x-xx-xxx-xxxxx',6)
console.log(myUuidv4es8())
console.log(myUuidv4es8())
//australian phone number:
myUuidv4es8 = uuidFactory('61-xxx-xxx-xxx',10)
console.log(myUuidv4es8())
console.log(myUuidv4es8())