萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 通過索引刪除數組元素:splice 核心用法與邊界處理

核心 API:Array.prototype.splice

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']

常見變體

1. 刪除多個連續索引

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);
}

2. 刪除多個離散索引(需逆序)

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(); // 保持原順序返回
}

3. 不可變版(返回新數組)

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 2this.list.splice(index, 1) (響應式)
Vue 3list.value.splice(index, 1) 或 list.value = list.value.filter((_, i) => i !== index)
ReactsetList(prev => prev.filter((_, i) => i !== index))
Sveltelist.splice(index, 1) (自動響應)

總結

splice 是原生數組按索引刪除的標準方法,核心注意點:

  1. 修改原數組,返回被刪元素數組
  2. 支援負數索引(從末尾倒數)
  3. 多索引刪除必須降序處理避免索引偏移
  4. 現代框架優先使用不可變 filter/slice 組合觸發響應式更新
copyright © 萬盛學電腦網 all rights reserved