在 JavaScript 中生成指定长度的随机字符串

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 19:24:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字 n,并返回一个长度为 n 的随机字符串,该字符串不包含除 26 个英文小写字母之外的任何内容。

因此,让我们编写该函数代码 −

示例

其代码为 −

const num = 8;
const randomNameGenerator = num => {
   let res = '';
   for(let i = 0; i < num; i++){
      const random = Math.floor(Math.random() * 27);
      res += String.fromCharCode(97 + random);
   };
   return res;
};
console.log(randomNameGenerator(num));

输出

控制台中的输出将是 −

kdcwping

注意 − 这是许多可能的输出之一。控制台输出每次都应有所不同。


相关文章


有用资源