JavaScript Array splice vs slice

后端 未结 15 1276
刺人心
刺人心 2020-11-28 17:56

What is the difference between splice and slice?

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


        
相关标签:
15条回答
  • 2020-11-28 18:32

    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.

    0 讨论(0)
  • 2020-11-28 18:33

    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);

    0 讨论(0)
  • 2020-11-28 18:33

    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.

    0 讨论(0)
提交回复
热议问题