Array.splice() ใช้เพิ่ม ลบ หรือแทนที่ Element ใน Array โดยเปลี่ยน Array ต้นฉบับ (Mutate) และคืนค่า Array ของ Element ที่ถูกลบ
ไวยากรณ์
array.splice(startIndex, deleteCount, item1, item2, ...)
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Splice Example</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample, .result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Splicing an array in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to add items after 2nd element </h3>
<script>
let fillEle = document.querySelector(".sample");
let resEle = document.querySelector(".result");
let arr = [1, 3, 5, 7, 9, 11];
fillEle.innerHTML = arr;
document.querySelector(".Btn").addEventListener("click", () => {
arr.splice(2, 0, "A", "B", "C", "D", "E");
resEle.innerHTML = "Spliced array = " + arr;
});
</script>
</body>
</html>
คำอธิบายตัวอย่าง
splice(2, 0, "A", "B", "C", "D", "E"): เริ่ม Index 2, ลบ 0 ตัว, เพิ่ม A-E- Array เดิม: [1, 3, 5, 7, 9, 11] → ใหม่: [1, 3, A, B, C, D, E, 5, 7, 9, 11]
กรณีการใช้งานอื่น
- ลบ:
arr.splice(1, 2)ลบ 2 ตัวจาก Index 1 - แทนที่:
arr.splice(1, 2, 'X', 'Y')ลบ 2 ตัว แล้วเพิ่ม X, Y
ผลลัพธ์
ก่อน: [1, 3, 5, 7, 9, 11] | หลัง: [1, 3, A, B, C, D, E, 5, 7, 9, 11]