📌  相关文章
📜  JavaScript 中的 Array.slice() 和 Array.splice() 有什么区别?

📅  最后修改于: 2022-05-13 01:56:43.035000             🧑  作者: Mango

JavaScript 中的 Array.slice() 和 Array.splice() 有什么区别?

Javascript 数组是可以保存多个值的变量。有许多与这些数组相关的方法。方法 slice() 和 splice() 是广泛使用的数组操作方法。它们之间存在各种差异,如下表所示。

slice()splice()
This method is used to get a new array by selecting a sub-array of a given array.This method is used to add/remove an item from the given array.
The parameter ‘s’ indicates the starting index and ‘e’ indicates the ending index. They denote the index of the sub-array to be taken. By default, the value for start is ‘0’ and end is ‘n’.The parameter ‘i’ denotes the starting index, ‘n’ denotes the number of items to be removed from the specified starting index.‘item 1, item 2, …..item n’ represents the list of new items to be added at the given index. If n=0, no item is removed, the new items are just added to the specified starting index.
The changes do not reflect in the original array.The changes reflect in the original array
The result has to be assigned to a new array variable.The result need not be assigned to any other new variable.
The return value is new array with the values in the selected sub-array of the given array. The values in the range start to (end-1) will be selected.The return value is an array containing the deleted element.
Takes exactly 2 argumentsTakes ‘n’ number of arguments (a list of new items can be supplied)

句法:

  • 片():
    array_name.slice(s, e)
  • 拼接():
    array_name.splice(i, n, item 1, item 2, .....item n)

slice() 方法的示例
示例 1:同时指定了开始和结束。


输出:

cars :Benz, Innova, Breeza, Etios, Dzire
new_cars :Innova, Breeza, Etios

示例 2:仅指定开始。 end 默认情况下是数组的长度。


输出:

cars :Benz, Innova, Breeza, Etios, Dzire

new_cars :Breeza, Etios, Dzire

splice() 方法的示例
示例 1:现在让我们添加更多项目,但不删除任何项目。


输出:

cars :Benz, Innova, ambassedor, BMW, Audi, Breeza, Etios, Dzire

示例 2:删除一个元素而不添加任何新项目


输出:

cars :Benz, Innova, BMW, Audi, Breeza, Etios, Dzire

示例 3:删除多个元素并且不添加任何新项目。


输出:

cars :Benz, Innova, Breeza, Etios, Dzire

在删除多个元素时,在上述情况下,指定的起始索引为“2”,并且需要删除“3-elements”,因此它开始从索引本身中删除元素。因此,索引 2、3 和 4 中的项目被删除。