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