Viết hàm nhận vào chuỗi và số n, trả về chuỗi mới với mỗi ký tự được lặp lại n lần.
Ví dụ
Chuỗi: 'how are you', n = 2
Kết quả: 'hhooww aarree yyoouu'
Giải pháp
Mã triển khai dùng String.prototype.repeat():
const str = 'how are you';
const repeatNTimes = (str, n) => {
let res = '';
for (let i = 0; i < str.length; i++) {
res += str[i].repeat(n);
}
return res;
};
console.log(repeatNTimes(str, 2));
Kết quả
Đầu ra trong console:
hhooww aarree yyoouu
Viết ngắn gọn: str.split('').map(c => c.repeat(n)).join('')