Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การทำซ้ำสตริงใน JavaScript

คำอธิบาย

ใช้ Array() ร่วมกับ join() เพื่อทำซ้ำสตริงจำนวนครั้งที่กำหนด

ตัวอย่างโค้ด

<script>
String.prototype.counter = function (value) {
  return new Array(value + 1).join(this);
};
console.log("The repeat string\n".counter(5));
</script>

ผลลัพธ์

พิมพ์ "The repeat string" 5 บรรทัดใน console