【问题标题】:How to get a random number/letter combination in Javascript? [duplicate]如何在Javascript中获取随机数字/字母组合? [复制]
【发布时间】:2020-04-19 04:59:15
【问题描述】:

我正在尝试创建一个使用 javascript(在浏览器控制台中)将随机数字/字母放入文本框中的程序。我已经尽力做到了,但我就是做不到。

我最好的尝试是:

var key = ((nums[Math.floor(Math.random() * nums.length)].toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));
var key2 = ((Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));
var key3 = ((Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));

但不幸的是它只生成数字。有谁知道如何随机化两者?如果有人可以帮助我,将不胜感激。

问候,3hr3nw3rt

【问题讨论】:

    标签: javascript variables random numbers letter


    【解决方案1】:

    您可以使用生成字母数字字符串

    function alphaNumericString(length) {
        var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            retVal = "";
        for (var i = 0, n = charset.length; i < length; ++i) {
            retVal += charset.charAt(Math.floor(Math.random() * n));
        }
        return retVal;
    }
    
    console.log(alphaNumericString(3))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-31
      • 2013-04-12
      • 1970-01-01
      • 2011-01-29
      • 2012-12-16
      • 2012-05-30
      • 2013-03-25
      • 2017-11-05
      相关资源
      最近更新 更多