写一个方法,批量删除指定索引的数组元素

/**
 * 批量删除数组中指定索引的元素。
 *
 * @param {Array} arr 原数组
 * @param {Array<number>} indices 要删除的元素的索引数组,必须按升序排列
 * @returns {Array} 删除元素后的新数组,不会修改原数组
 */
function removeElementsAtIndexes(arr, indices) {
  if (!Array.isArray(arr) || !Array.isArray(indices)) {
    throw new TypeError("Both arguments must be arrays.");
  }

  if (!indices.every(Number.isInteger)) {
    throw new TypeError("Indices must be integers.");
  }

  // 判断indices是否有序
  for (let i = 1; i < indices.length; i++) {
    if (indices[i] <= indices[i - 1]) {
      throw new Error("Indices must be sorted in ascending order.");
    }
  }


  const newArr = [];
  let currentIndex = 0;
  let deleteIndex = 0;

  for (let i = 0; i < arr.length; i++) {
    if (deleteIndex < indices.length && i === indices[deleteIndex]) {
      // 跳过要删除的元素
      deleteIndex++;
    } else {
      // 保留的元素添加到新数组
      newArr[currentIndex++] = arr[i];
    }
  }

  return newArr;
}



// 测试用例
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// 删除索引 2, 4 的元素
const indices1 = [2, 4];
const result1 = removeElementsAtIndexes(arr, indices1);
console.log(result1); // Output: ['a', 'b', 'd', 'f', 'g']

// 删除索引 0, 1, 6 的元素
const indices2 = [0, 1, 6];
const result2 = removeElementsAtIndexes(arr, indices2);
console.log(result2); // Output: ['c', 'd', 'e', 'f']


//  indices 非法输入的测试用例

// indices 不是数组
console.log(removeElementsAtIndexes(arr, "test")); // Throws TypeError
console.log(removeElementsAtIndexes(arr, 1)); // Throws TypeError

// indices 元素不是整数
console.log(removeElementsAtIndexes(arr, [1, 2.5])); // Throws TypeError

// indices 不是升序
console.log(removeElementsAtIndexes(arr, [2, 1])); // Throws Error


// 空数组和空索引的测试用例
console.log(removeElementsAtIndexes([], []));  // Output: []
console.log(removeElementsAtIndexes(arr, [])); // Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] (same as original array)



这个改进的版本包含了以下几点:

  • 错误处理: 增加了对非法输入(arrindices 不是数组,indices 包含非整数,indices 不是升序)的处理,并抛出相应的错误信息。
  • 类型检查: 使用 Array.isArray()Number.isInteger() 进行更严格的类型检查。
  • 效率: 使用一个 deleteIndex 变量来跟踪要删除的索引,避免了不必要的循环或数组操作,提高了效率,尤其是在要删除的元素较多时。
  • 清晰的注释: 添加了更详细的注释,解释函数的功能、参数和返回值。
  • 全面的测试用例: 添加了更多的测试用例,覆盖了各种情况,包括非法输入、空数组、空索引等。

这个版本更加健壮、高效,并且更容易理解和使用。

posted @ 2024-12-13 09:19  王铁柱6  阅读(39)  评论(0)    收藏  举报