问题描述
通过使用Math.random()函数单击一个按钮,我可以一次创建一个字母数字字符串。
但是我需要通过单击按钮来一次打印5个字母数字随机值。 请帮帮我,我是javascript的新手,被卡住了。 我真的需要一些解决方案
解决方法
通过在以10为底的基础上生成随机数,然后将其转换为以36为底的数字,该数字包括数字和字母(10位+ 26字母= 36)来实现。
'use strict';
document.querySelector('button').onclick = function () {
const strings = new Array(5)
.fill()
.map(() => Math.random() * 10000)
.map((n) => n.toString(36).replace(/\./,''));
console.log(strings);
}
<button>Click</button>
,
这有效:生成Math.random
在65到100之间的随机数(ASCII:A-Z,数字再增加10),然后生成useString.fromCharCode
将其转换为char。为了获得数字子句,如果随机数大于90,则以ASCII码表示的差异。使用for循环并添加字符。
document.getElementById('btn').addEventListener('click',() => {
let random = '';
for (let x = 0; x < 5; x++) {
let randInt = Math.floor((Math.random() * 35) + 65);
random += String.fromCharCode((randInt<=90) ? randInt : randInt-43);
}
document.getElementById('random').textContent=random;
});
<button id='btn'>Random</button>
<div id='random'></div>