重复字母字符串 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 2:52:17

我们需要编写一个 JavaScript 函数,该函数接受一个字符串和一个数字(例如 n),并且该函数应返回一个新字符串,其中原始字符串的所有字母都重复了 n 次。

例如:如果字符串是 −

const str = 'how are you'

数字 n 是 2

那么输出应该是 −

const output = 'hhooww  aarree  yyoouu'

示例

以下是代码 −

const str = 'how are you';
const repeatNTimes = (str, n) => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      // using the String.prototype.repeat() function
      res += str[i].repeat(n);
   };
   return res;
};
console.log(repeatNTimes(str, 2));

输出

以下是控制台中的输出 −

hhooww  aarree  yyoouu

相关文章


有用资源