What is the difference between splice
and slice
?
$scope.participantForms.splice(index, 1);
$scope.participantForms.slice(index, 1);
Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.
splice()
changes the original array whereas slice()
doesn't but both of them returns array object.
See the examples below:
var array=[1,2,3,4,5];
console.log(array.splice(2));
This will return [3,4,5]
. The original array is affected resulting in array
being [1,2]
.
var array=[1,2,3,4,5]
console.log(array.slice(2));
This will return [3,4,5]
. The original array is NOT affected with resulting in array
being [1,2,3,4,5]
.
Below is simple fiddle which confirms this:
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
The slice() method returns a copy of a portion of an array into a new array object.
$scope.participantForms.slice(index, 1);
This does NOT change the participantForms
array but returns a new array containing the single element found at the index
position in the original array.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
$scope.participantForms.splice(index, 1);
This will remove one element from the participantForms
array at the index
position.
These are the Javascript native functions, AngularJS has nothing to do with them.