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

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

当前回答

两者都返回相同的答案,但是:

SPlice将改变原始数组。 Slice不会改变原始数组。

其他回答

两者都返回相同的答案,但是:

SPlice将改变原始数组。 Slice不会改变原始数组。

这里有一个简单的技巧来记住切片和拼接之间的区别

var a=['j','u','r','g','e','n'];

// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]

//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]

要记住的技巧:

将“spl”(splice的前3个字母)视为“指定长度”的缩写,即第二个参数应该是长度而不是索引

/ /拼接 数组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);

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.

另一个例子:

[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]