我正在尝试编写一个从提供的字符串中生成随机序列号的函数。
此函数创建随机序列,它有20个数字,但是此函数不输出随机序列,却输出20个数字,为什么?
var char = "123456ABCDEFGHI76wndixdzsfszfs2009765210ojfngdBNMUOP",
cenrate = document.getElementById('gen'),
ser = document.getElementById('seriel'),
serialLenght = 20,
i,
randomKey;
window.onclick = function eee() {
'usesrtict';
randomKey = Math.floor(Math.random() * char.length);
// console.log(randomKey);
for (i = 0; i < serialLenght; i++) {
randomKey = char.substring(randomKey, randomKey + 1);
}
// document.getElementById('seriel').textContent=randomKey
console.log(randomKey)
}
<button id="cen">Generate</button>
<div id="seriel"></div>
如果要尝试生成一个20个字符长的随机字符串,则必须在for循环中生成一个随机字符,并将结果连接到最终字符串中,如下所示:
var char="123456ABCDEFGHI76wndixdzsfszfs2009765210ojfngdBNMUOP",
cenrate=document.getElementById('gen'),
ser=document.getElementById('seriel'),
serialLenght = 20,
i,
randomKey;
window.onclick=function eee(){
'usesrtict';
finalString = "";
// console.log(randomKey);
for(i=0;i<serialLenght; i++){
randomKey= Math.floor(Math.random()*char.length);
finalString+=char.substring(randomKey,randomKey+1);
}
// document.getElementById('seriel').textContent=randomKey
console.log(finalString)
}
<button id="cen">Ganarete</button>
<div id="seriel"></div>
您可以通过执行for循环并将随机选择的索引处的字符添加到初始化的字符串中来实现。可以通过下一行完成随机化。
Math.floor(Math.random() * chars.length)
您只产生一个随机数,您需要产生一个20次随机数,因为这是您要产生的序列号的长度。
var chars = "123456ABCDEFGHI76wndixdzsfszfs2009765210ojfngdBNMUOP",
cenrate = document.getElementById('gen'),
ser = document.getElementById('seriel'),
serialLenght = 20,
i,
randomKey;
genSerialNum = () => {
var serialNum = ''
for (var i = 0; i < 20; ++i) {
var char = chars[Math.floor(Math.random() * chars.length)];
serialNum += char
}
console.log(serialNum)
}
genSerialNum()