拼接和切片的区别是什么?
const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
拼接和切片的区别是什么?
const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
当前回答
大多数答案都太啰嗦了。
拼接和切片返回数组中其余的元素。 拼接使被操作的数组发生突变,删除元素,而切片没有。
其他回答
另一个例子:
[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]
[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]
切片和拼接紧密相连,但用途却截然不同:
slice函数用于选择数组的一部分。它的目的是返回值。它的执行并不影响它的主题。
splice函数用于从数组中删除元素。它的目的是修饰它的主题。如果需要,它仍然返回已删除项的副本,以供参考。
有3个不同点:
Splice将从原始数组中删除所选元素,并将它们作为一个新数组返回-请注意,原始数组将不再拥有它们-。Slice将使用所选元素创建一个新数组,而不会影响原来的数组。 Splice接收起始索引和从该点移除多少元素作为参数。Slice接收2个索引,开始和结束。 Splice可用于通过传递可选参数在数组中的特定位置添加元素。
大多数答案都太啰嗦了。
拼接和切片返回数组中其余的元素。 拼接使被操作的数组发生突变,删除元素,而切片没有。
splice()方法返回数组中已删除的项。 slice()方法将数组中所选的元素作为一个新的数组对象返回。
splice()方法改变原始数组,slice()方法不改变原始数组。
Splice() method can take n number of arguments: Argument 1: Index, Required. Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed. Argument 3..n: Optional. The new item(s) to be added to the array. slice() method can take 2 arguments: Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array. Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.