如何从 JavaScript 中的 ASCII 字符生成随机字符串

如何构建一个简单的字符串生成器,通过在 ASCII 表中键入 ASCII-character-number-range 来创建和打印 10 个字符的随机字符串,包括小写和大写字母、数字和 ASCII 表的 0 到 127 之间的特殊字符方法?不是像这样的变量


    var possibleCharacters = "01234567890abcdefgh....."

我的一个朋友已经用 Java 构建了它(见下文),那么我如何在 JavaScript 中构建它,也像 Java 示例中那样使用 for 循环?


    public class Main {

public static void main(String[] args) {

    for (int counter = 0; counter <= 9; counter++) {

        int randomNum = 0 + (int)(Math.random() * 127);

        if(randomNum > 33) {

            System.out.print((char)randomNum);

        }else {

            counter--;

        }

    }

}

}

它应该只生成类似“_e7N?:G&M0”的东西,即


江户川乱折腾
浏览 221回答 1
1回答

慕的地10843

返回随机字符串的函数:function getString() {&nbsp; var str = "";&nbsp; for (counter = 0; counter <= 9; counter++) {&nbsp; &nbsp; var randomNum = 0 + parseInt(Math.random() * 127);&nbsp; &nbsp; if (randomNum > 33) {&nbsp; &nbsp; &nbsp; str += String.fromCharCode(randomNum);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; counter--;&nbsp; &nbsp; }&nbsp; }&nbsp; return str;}for (i = 0; i < 10; i++)&nbsp; console.log(getString());如果您尝试生成 33 到 127 之间的数字:function getString() {&nbsp; var str = "";&nbsp; for (counter = 0; counter <= 9; counter++) {&nbsp; &nbsp; var randomNum = 0 + parseInt(Math.floor(Math.random() * (127 - 33 + 1) + 33));&nbsp; &nbsp; str += String.fromCharCode(randomNum);&nbsp; }&nbsp; return str;}for (i = 0; i < 10; i++)&nbsp; console.log(getString());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript