JavaScript 中 n 次運球字串
我們需要編寫一個 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP