使用javascript生成唯一的随机字母数字

Generate unique random alphanumeric using javascript

本文关键字:随机 数字 唯一 javascript 使用      更新时间:2023-09-26

代码:

function alphanumeric()
{
var randomnum=Math.random().toString(36).substr(2,8);
document.getElementbyId("textBoxId").value = randomnum;
}

每次调用alphannumeric((函数时,它都会生成字母数字随机字符串,并显示在文本框上,如。。v3ta4t8l、zshqoc2u、9pey71rb。。。这很好用。。在我的要求中,我只需要允许唯一的字母数字。,你能帮我解决以下问题吗

1.是否只生成唯一的字母数字?

2.这将生成多少个字母数字?

3.是否可以只允许唯一的字母数字?

4.在数据库中使用主键存储唯一的字母数字是可能的,在我的情况下,我的一列已经有主键了,所以我将尝试使用java脚本来实现。。。

以下是只返回唯一字母数字的内容

function alphanumeric_unique() {
    return Math.random().toString(36).split('').filter( function(value, index, self) { 
        return self.indexOf(value) === index;
    }).join('').substr(2,8);
}

FIDDLE

将字符串拆分为一个字符数组,然后使用Array.filter()过滤掉数组中已经存在的任何字符,只获得每个字符的一个实例,最后将这些字符连接回一个字符串,并运行substr(2, 8)获得与问题中相同长度的字符串,从第二个字符开始,总共获得八个字符。

 function IDGenerate() {
        var text = "";
        var hdntxt = "";
        var captchatext = "";
        var possible = "ABCDEFGHIkLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0; i < 7; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));         
        }
        document.getElementById("txtboxID").value = text;
        return false;
    }