เมธอด fill() ใช้สำหรับ เติมค่าคงที่ (static value) ให้กับองค์ประกอบในอาร์เรย์ ภายในช่วงดัชนีที่ระบุ อาร์เรย์เดิมจะถูกแก้ไขโดยตรง (mutate)
ไวยากรณ์ (Syntax)
array.fill(value[, start[, end]])
value- ค่าที่จะเติมstart(ตัวเลือก) - ดัชนีเริ่มต้น (ค่าเริ่มต้น: 0)end(ตัวเลือก) - ดัชนีสิ้นสุด (ไม่รวม ดัชนีนี้) (ค่าเริ่มต้น:array.length)
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: เติมทั้งอาร์เรย์
<!DOCTYPE html>
<html>
<body>
<h2>คะแนนอันดับ</h2>
<button onclick="display()">เติมค่า 1000</button>
<p id="demo"></p>
<script>
let pointsArr = [50, 100, 200, 300, 400, 500, 600];
document.getElementById("demo").innerHTML = pointsArr;
function display() {
pointsArr.fill(1000);
document.getElementById("demo").innerHTML = pointsArr;
// ผลลัพธ์: 1000,1000,1000,1000,1000,1000,1000
}
</script>
</body>
</html>
ตัวอย่างที่ 2: เติมเฉพาะช่วง (start, end)
<!DOCTYPE html>
<html>
<body>
<h2>ชื่อนักเรียน</h2>
<button onclick="display()">เติม "Jacob" ตำแหน่ง 1-2</button>
<p id="demo"></p>
<script>
let stdName = ["John", "Tom", "David"];
document.getElementById("demo").innerHTML = stdName;
function display() {
// เริ่มที่ดัชนี 1 จนถึงดัชนี 3 (ไม่รวม 3) = เติมแค่ดัชนี 1 และ 2
stdName.fill("Jacob", 1, 3);
document.getElementById("demo").innerHTML = stdName;
// ผลลัพธ์: John,Jacob,Jacob
}
</script>
</body>
</html>
ตัวอย่างที่ 3: สร้างอาร์เรย์ใหม่พร้อมค่าเริ่มต้น
// สร้างอาร์เรย์ 5 ช่อง เติม 0 ทั้งหมด
const zeros = new Array(5).fill(0); // [0,0,0,0,0]
// สร้างเมทริกซ์ 3x3 (ระวัง: ใช้ fill กับอาร์เรย์จะได้ reference เดียวกัน!)
const matrix = Array.from({length: 3}, () => new Array(3).fill(0));
// ถูกต้อง: แต่ละแถวเป็นอาร์เรย์คนละตัว
ข้อควรระวัง: Reference กับ Object/Array
// ❌ ผิด: ทุกช่องชี้ไปอ็อบเจกต์เดียวกัน
const wrong = new Array(3).fill({});
wrong[0].a = 1;
console.log(wrong); // [{a:1}, {a:1}, {a:1}] - เปลี่ยนทั้งหมด!
// ✅ ถูกต้อง: ใช้ map หรือ Array.from
const correct = Array.from({length: 3}, () => ({}));
correct[0].a = 1;
console.log(correct); // [{a:1}, {}, {}]