【问题标题】:How to print 5 random alphanumeric strings on one click in Javascript?如何在Javascript中一键打印5个随机字母数字字符串?
【发布时间】:2020-09-02 17:37:46
【问题描述】:

我可以通过使用 Math.random() 函数单击按钮一次创建单个字母数字字符串。

但我需要通过单击按钮一次打印 5 个字母数字随机值。 请帮助我,我是 javascript 的初学者并且被卡住了。 我真的需要一些解决方案

【问题讨论】:

  • for (let x = 0; x < 5; x++) { ... do your logic ... }

标签: javascript loops random generator alphanumeric


【解决方案1】:

这是通过生成以 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>

【讨论】:

    【解决方案2】:

    这有效:生成随机数,Math.random 介于 65 和 100 之间(ASCII:A-Z 和 10 多个数字)和useString.fromCharCode 将其转换为字符。如果随机数大于 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>

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多