拼接和切片的区别是什么?

const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);

当前回答

大多数答案都太啰嗦了。

拼接和切片返回数组中其余的元素。 拼接使被操作的数组发生突变,删除元素,而切片没有。

其他回答

Splice和Slice是内置的Javascript命令,而不是特定的AngularJS命令。Slice返回从“start”到“end”说明符之前的数组元素。Splice改变实际的数组,从“start”开始,并保持指定的元素数量。谷歌有很多这方面的信息,只要搜索。

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.

拼接- MDN参考- ECMA-262规范

语法 数组中。拼接(item1[[开始,deleteCount[第二条 [, ...]]]])

参数

开始:必需的。初始索引。 如果start为负,则将其视为“Math.max((数组。长度+ start), 0)”,按照规范(下面提供的示例)有效地从数组的末尾开始。 deleteCount:可选的。要删除的元素数量(如果没有提供,则全部从开始删除)。 Item1, item2,…:可选的。要从起始索引添加到数组的元素。

返回:删除元素的数组(如果没有删除则为空数组)

改变原始数组:是的

例子:

Const数组= [1,2,3,4,5]; //删除第一个元素 console.log('已删除的元素:',数组。Splice(0,1), '突变数组:',数组); //元素删除:[1]mutated array: [2,3,4,5] // array = [2,3,4,5] //删除最后一个元素start ->数组。长度+起始= 3) console.log('已删除的元素:',数组。Splice(- 1,1), '突变数组:',数组); //元素删除:[5]mutated array: [2,3,4]

更多的例子在MDN拼接的例子


切片- MDN参考- ECMA-262规范

语法 数组中。片([[,]]开始) 参数

开始:可选的。初始索引(默认为0)。 如果begin为负数,则将其处理为“Math.max((数组。长度+ begin), 0)”按照规范(下面提供的示例)有效地从数组的末尾开始。 结束:可选的。抽取的最后一个索引,但不包括(default array.length)。如果end为负数,则将其处理为“Math.max((数组。长度+ begin),0)”按照规范(下面提供的示例)有效地从数组的末尾开始。

返回:包含已提取元素的数组。

突变原:没有

例子:

Const数组= [1,2,3,4,5]; //提取第一个元素 console.log('提取的元素:',数组。Slice (0,1), 'array:', array); //元素提取:[1]array: [1,2,3,4,5] //提取最后一个元素start ->数组。长度+起始= 4) console.log('提取的元素:',array.slice(-1), 'array:', array); //元素提取:[5]array: [1,2,3,4,5]

更多的例子在MDN切片的例子

性能比较

不要认为这是绝对的真理,因为根据不同的场景,一个可能比另一个表现更好。 性能测试

切片和拼接紧密相连,但用途却截然不同:

slice函数用于选择数组的一部分。它的目的是返回值。它的执行并不影响它的主题。

splice函数用于从数组中删除元素。它的目的是修饰它的主题。如果需要,它仍然返回已删除项的副本,以供参考。

/ /拼接 数组var =[1、2、3、4、5); console.log (array.splice (2)); / /片 var array2 =[1、2、3、4、5) console.log (array2.slice (2)); console.log(“——后——”); console.log(数组); console.log (array2);