JavaScript 生成随机字母数字字符串的两种方法


发布日期 : 2020-03-22 20:45:17 UTC

访问量: 10 次浏览

在本文中,我们使用JavaScript生成指定长度的字母数字串,以下是一些常见的方法

方法1

  • 创建一个函数,该函数接受两个参数,一个是要生成的字符串的长度,另一个是要在字符串中出现的字符。
  • 声明一个新变量 ans = ""
  • 使用for循环以逆序遍历字符串。
  • 使用JavaScript的 Math.random() 方法生成随机索引,并与字符串的长度相乘。
  • 使用JavaScript的 Math.floor() 进行四舍五入,并将其添加到 ans 中。

示例1:
此示例使用 Math.random() 方法生成随机索引,然后将其添加到我们传递的字符串中。

function randomStr(len, arr) {
    let ans = '';
    for (let i = len; i > 0; i--) {
        ans +=
            arr[(Math.floor(Math.random() * arr.length))];
    }
    console.log(ans);
}
 
randomStr(20, '12345abcde');

输出

eecedee32d5245ba5ee3

方法2

  • 首先使用 Math.random() 方法生成一个随机数。
  • 使用JavaScript的 toString(36) 将其转换为基数36(26个字母+0到9的数字)的字符串。
  • 使用JavaScript的 String.slice() 方法获取字符串从位置2开始的部分。

示例2:
此示例首先生成一个随机数(0-1),然后使用 toString(36) 方法将其转换为基数36的字母数字字符串。

function GFG_Fun() {
    console.log(
        Math.random().toString(36).slice(2));
}
GFG_Fun()

输出

vv1lcnuwtm