arr.splice(startIndex, deleteCount[, item1, item2, ...])
// 從 startIndex 刪除 deleteCount 項,可選插入新項
// 返回:被刪除元素組成的數組
// 原數組被修改
/**
* 刪除指定索引處的元素
* @param {Array} arr - 目標數組
* @param {number} index - 索引(0 基礎,負數從末尾倒數)
* @returns {Array} 被刪除的元素數組
*/
function removeAt(arr, index) {
// 統一處理負數索引
if (index < 0) index = arr.length + index;
// 邊界檢查
if (index < 0 || index >= arr.length) return [];
return arr.splice(index, 1);
}
// 使用
var test = ['Apple', 'Ball', 'Cat', 'Dog'];
removeAt(test, 2); // 刪除 'Cat' (索引 2)
console.log(test); // ['Apple', 'Ball', 'Dog']
function removeRange(arr, start, count) {
if (start < 0) start = arr.length + start;
if (start < 0) start = 0;
if (start >= arr.length) return [];
count = Math.min(count, arr.length - start);
return arr.splice(start, count);
}
function removeAtIndices(arr, indices) {
// 索引去重 + 降序排列
var uniqueSorted = [...new Set(indices)].sort((a, b) => b - a);
var removed = [];
uniqueSorted.forEach(function(idx) {
if (idx >= 0 && idx < arr.length) {
removed.push(arr.splice(idx, 1)[0]);
}
});
return removed.reverse(); // 保持原順序返回
}
const removeAtImmutable = (arr, index) =>
index < 0 || index >= arr.length ? arr
: [...arr.slice(0, index), ...arr.slice(index + 1)];
// 批量不可變刪除
const removeIndicesImmutable = (arr, indices) => {
const removeSet = new Set(indices.map(i => i < 0 ? arr.length + i : i));
return arr.filter((_, i) => !removeSet.has(i));
};
<!DOCTYPE html>
<html><head><meta charset="utf-8"></head><body>
<pre id="out"></pre>
<script>
var test = ['Apple', 'Ball', 'Cat', 'Dog'];
function removeAt(arr, index) {
if (index < 0) index = arr.length + index;
if (index < 0 || index >= arr.length) return [];
return arr.splice(index, 1);
}
document.getElementById('out').textContent =
'原始: ' + JSON.stringify(['Apple', 'Ball', 'Cat', 'Dog']) + '\n' +
'刪除索引 2: ' + JSON.stringify(removeAt(test.slice(), 2)) + '\n' +
'剩餘數組: ' + JSON.stringify(test) + '\n' +
'負數索引 -1 (刪除最後): ' + JSON.stringify(removeAt(['a','b','c'], -1)) + '\n' +
'越界索引 10: ' + JSON.stringify(removeAt(['a','b','c'], 10));
</script>
</body></html>
| 框架 | 推薦寫法 |
|---|---|
| Vue 2 | this.list.splice(index, 1) (響應式) |
| Vue 3 | list.value.splice(index, 1) 或 list.value = list.value.filter((_, i) => i !== index) |
| React | setList(prev => prev.filter((_, i) => i !== index)) |
| Svelte | list.splice(index, 1) (自動響應) |
splice 是原生數組按索引刪除的標準方法,核心注意點:
filter/slice 組合觸發響應式更新