在Javascript中如何获得一个随机的数字/字母组合?
在Javascript中如何获得一个随机的数字/字母组合?
我正在尝试使用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中生成一个随机的字母和数字的组合。
解决方法是使用以下Javascript函数来生成一个指定长度的字母和数字的组合:
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))
这个函数接受一个参数length,表示生成的组合的长度。在函数内部,我们定义了一个包含字母和数字的字符集charset。然后,我们使用一个循环来随机选择字符集中的字符,并将它们拼接到返回值retVal中。最后,我们返回生成的组合。
在上面的例子中,我们调用了alphaNumericString函数,并传入长度为3。函数生成了一个长度为3的随机字母和数字的组合,并将结果打印到控制台上。您可以根据需要调整生成的组合的长度。