在 JavaScript 中用随机小写字母填充字符串以填充长度

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 20:28:17

我们需要编写一个接受两个参数的函数,第一个是字符串,第二个是数字。字符串的长度始终小于或等于数字。我们必须在字符串末尾插入一些随机小写字母,使其长度恰好等于数字,然后我们必须返回新字符串。

示例

让我们来编写该函数的代码 −

const padString = (str, len) => {
   if(str.length < len){
      const random = Math.floor(Math.random() * 26);
      const randomAlpha = String.fromCharCode(97 + random);
      return padString(str + randomAlpha, len);
   };
   return str;
};
console.log(padString('abc', 10));
console.log(padString('QWERTY', 10));
console.log(padString('HELLO', 30));
console.log(padString('foo', 10));

输出

控制台中的输出 −

abckoniucl
QWERTYcwaf
HELLOdnulywbogqhypgmylqlvmckhg
Foofhfnhon

相关文章


有用资源