首页 > 解决方案 > 如何获得随机数而不是随机数和字母?

问题描述

我想制作随机的三位数,但是当我运行它时,它会生成字母数字字符。我只想得到一个随机的三位数。

产生:

function () {
    this.newItem.st = Math.random().toString(36).substring(2, 3).toUpperCase() +
                      Math.random().toString(36).substring(2, 4).toUpperCase()
}

屏幕截图

当我单击生成时,我只想获得 0-9 而不是 AZ 的随机值。

标签: javascriptweb

解决方案


将你的随机数乘以 10 得到一个位置,使用 Math.floor 得到一个整数,然后转换为字符串得到一串数字:

const el = document.getElementById("output");
el.innerHTML = getNumber();
function getNumber() {
    let myNum = Math.floor(Math.random() * 10).toString() + Math.floor(Math.random() * 10).toString() + Math.floor(Math.random() * 10).toString();
    return  myNum;
}

推荐阅读