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

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

当前回答

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

其他回答

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

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个字母)视为“指定长度”的缩写,即第二个参数应该是长度而不是索引

有3个不同点:

Splice将从原始数组中删除所选元素,并将它们作为一个新数组返回-请注意,原始数组将不再拥有它们-。Slice将使用所选元素创建一个新数组,而不会影响原来的数组。 Splice接收起始索引和从该点移除多少元素作为参数。Slice接收2个索引,开始和结束。 Splice可用于通过传递可选参数在数组中的特定位置添加元素。

slice()方法将数组部分的副本返回到新的数组对象中。

$scope.participantForms.slice(index, 1);

这不会改变participantForms数组,而是返回一个包含原始数组中索引位置上的单个元素的新数组。

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

$scope.participantForms.splice(index, 1);

这将在索引位置从participantForms数组中删除一个元素。

这些是Javascript的原生函数,与AngularJS无关。

slice()方法复制数组的给定部分,并将复制的部分作为一个新数组返回。它不会改变原始数组。

splice()方法通过向数组中添加或删除元素来更改数组。

下面是切片语法:

array.slice(from, until);

// example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.slice(1, 3)
console.log({array, newArray})

// output: array: [1, 2, 3, 4, 5, 6], newArray: [2, 3]

注意:Slice()方法也可以用于字符串。

下面是拼接的语法:

//For removing elements, we need to give the index parameter,
// and the number of elements to be removed

array.splice(index, number of elements to be removed);


//example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.splice(1, 3)
console.log({array, newArray})

// output: array: [1, 5, 6], newArray: [2, 3, 4]

注意:如果不定义第二个形参,则从给定索引开始的每个元素都将从数组中删除

// For adding elements, we need to give them as the 3rd, 4th, ... parameter
array.splice(index, number of elements to be removed, element, element);

//example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.splice(1, 3, 'a', 'b')
console.log({array, newArray})

// output: array: [1, ,'a', 'b', 5, 6], newArray: [2, 3, 4]

相关链接:

让我们来澄清JavaScript中slice()、splice()和split()方法的混淆

Array.prototype.slice ()

Array.prototype.splice ()

Slice()和Splice() javascript内置函数之间的区别是, Slice返回删除的项,但没有改变原始数组; 就像,

        // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.slice(index)
        // result=4  
        // after slicing=>  array =[1,2,3,4,5]  (same as original array)

但在splice()情况下,它会影响原始数组;就像,

         // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.splice(index)
        // result=[4,5]  
        // after splicing array =[1,2,3]  (splicing affects original array)