JavaScript Array splice vs slice

后端 未结 15 1375
刺人心
刺人心 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:25

    slice does not change original array it return new array but splice changes the original array.

    example: var arr = [1,2,3,4,5,6,7,8];
             arr.slice(1,3); // output [2,3] and original array remain same.
             arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].
    

    splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.

    arr.splice(-3,-1); // output [] second argument value should be greater then 
    0.
    arr.splice(-3,-1); // output [6,7] index in minus represent start from last.
    

    -1 represent last element so it start from -3 to -1. Above are major difference between splice and slice method.

提交回复
热议问题