splice() 是陣列操作裡最靈活的方法之一,可以同時完成「刪除」與「插入」。本文聚焦在它最單純的用法:在指定索引處插入若干元素,且不刪除任何既有內容。
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add elements to the array.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
var x = document.getElementById("demo");
x.innerHTML = fruits;
}
</script>
</body>
</html>
執行結果:
Banana,Orange,Lemon,Kiwi,Apple,Mango
array.splice(startIndex, deleteCount, item1, item2, ...);
把 deleteCount 改成非 0,就變成「刪除並替換」:
var arr = ["a", "b", "c", "d"]; arr.splice(1, 2); // 刪掉 b、c → ["a", "d"],回傳 ["b", "c"] arr.splice(1, 0, "x"); // 純插入 → ["a", "x", "d"]
splice() 有兩個重點必須記住:它會直接改動原陣列(不是回傳新陣列),而且它回傳的是被刪除的元素所組成的新陣列。這兩點和 slice() 剛好相反,也是初學者最常搞混的地方。