为什么 .splice() 方法会删除不同索引的元素?

Why .splice() method deletes elements of different indexes?

这是我在Whosebug上的第一个问题,我是新手:)学习JS。我有个问题。我写了这个函数:

function inverseSlice(items, a, b) {
  return items.splice(a, b);
}
inverseSlice([1, 2, 3, 4, 5, 6], 2, 4)
(4) [3, 4, 5, 6]

为什么这个函数 return 是最后 4 位数字,根据 MDN 上的文档(我已经阅读了 10 次 :P) splice() 方法应该只删除中间的 2 个 (3, 4) ?它应该 return [1, 2, 5, 6]。我对吗?感谢您的帮助:)

splice

  • 改变原始数组:删除N项,其中N是第三个参数,从起始索引(第一个参数)开始到指定的数字(所以这里,它将从数组中删除索引2到5;指标 2、3、4 和 5,总共删除了 4 个)
  • Return 删除的元素 - 所以,这里是 [3, 4, 5, 6]

原始数组现在是 [1, 2],但您正在记录 .splice 返回的内容,而不是原始数组。

如果您想要 [1, 2, 5, 6],您需要为第三个参数指定 2(要删除 2 项),然后记录原始数组:

function inverseSlice(items, a, b) {
  return items.splice(a, b);
}
const arr = [1, 2, 3, 4, 5, 6];
const removedItems = inverseSlice(arr, 2, 2);

console.log(arr);
console.log(removedItems);

它做的正是它宣传的那样,它“returns 一个包含已删除元素的数组。”

function inverseSlice(items, a, b) {
  return items.splice(a, b);
}

let array = [1, 2, 3, 4, 5, 6, 7, 8];

// Deletes 4 entries starting at index 2,
// or in other words [3,4,5,6] are snipped
inverseSlice(array, 2, 4);

console.log(array);

除非您保留对传入数组的引用,否则您永远不会观察到它的最终结果,您只会得到已删除的元素。

你对 splice 的参数感到困惑,你传递给 splice 的两个参数不是开始和结束索引,而是 开始索引以及要删除的项目数.

因此在您的示例中,它从 2 到 5 索引中删除了项目并返回结果数组,即 [3, 4, 5, 6]

根据 docs:

Syntax:

let arrDeletedItems = arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

  • Start : The index at which to start changing the array.
  • deleteCount: n integer indicating the number of elements in the array to remove from start.
  • item1, item2, ... : The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.