เราจำเป็นต้องเขียนฟังก์ชัน 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