在 JavaScript 中生成具有特定长度的随机字符串
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数将数字作为唯一参数。然后,该函数应返回由参数指定长度的随机生成的字符串。
用于字符串生成的字符集应仅包含大写和小写字母(无空格、标点符号或数字)。
示例
其代码为 −
const num = 13;
const randomString = (len = 1) => {
const charSet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let randomString = '';
for (let i = 0; i < len; i++) {
let randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
};
return randomString;
};
console.log(randomString(num));
输出
控制台中的输出将是 −
EqprjcudAhmVg
每次运行的输出可能会有所不同。
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

