[英]Generate unique 5 character string?
如何在 javascript 中生成唯一(非隨機)5 字符串。 我不想使用 Math.random() 因為它不能確保唯一性。 它應包含 az、AZ 和 0-9 中的字符。 字符可以重復但字符串不能重復,字符串不會再次生成。
我想這就是你想要的。 取到字符串后彈出字符,不能再取出,保證唯一性。
function makeid(length) {
var result = '';
var characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
var charactersLength = characters.length;
for (var i = 0; i < length; i++ ) {
var randomIndex = Math.floor(Math.random() * charactersLength);
while (randomIndex > charactersLength) {
var randomIndex = Math.floor(Math.random() * charactersLength);
}
result += characters[randomIndex];
if (randomIndex > -1) {
characters.splice(randomIndex, 1);
}
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.