JavaScript 程序:生成随机字符串
要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:
示例 1:生成随机字符串
// 程序生成随机字符串
// 声明所有字符
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
function generateString(length) {
let result = " ";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(generateString(5));
输出
B5cgH
在上述示例中,使用 Math.random()
方法从指定的字符 (A-Z, a-z, 0-9) 中 生成随机字符。
for
循环用于循环遍历传递给 generateString()
函数的数字。在每次迭代期间,生成一个随机字符。
示例 2:使用内置方法生成随机字符串
// 程序生成随机字符串
const result = Math.random().toString(36).substring(2, 7);
console.log(result);
输出
gyjvo
在上述示例中,使用内置方法生成随机字符。
Math.random()
方法生成介于 0 和 1 之间的随机数。
在 toString(36)
方法中,36 代表 基数 36。toString(36)
使用字母表示 9 之后的数字。
substring(2, 7)
方法返回五个字符。
注意:在上述示例中,每次执行时输出都会不同,因为每次都在生成随机字符。