Repeating letter string - JavaScript
我們需要編寫一個 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
廣告