JavaScript 中 n 次重复的字符串
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 0:44: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++){
// 使用 String.prototype.repeat() 函数
res += str[i].repeat(n);
};
return res;
};
console.log(repeatNTimes(str, 2));
控制台中的输出将是 −
hhooww aarree yyoouu
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

