JavaScript Array splice vs slice

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

    Splice - MDN reference - ECMA-262 spec

    Syntax
    array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

    Parameters

    • start: required. Initial index.
      If start is negative it is treated as "Math.max((array.length + start), 0)" as per spec (example provided below) effectively from the end of array.
    • deleteCount: optional. Number of elements to be removed (all from start if not provided).
    • item1, item2, ...: optional. Elements to be added to the array from start index.

    Returns: An array with deleted elements (empty array if none removed)

    Mutate original array: Yes

    Examples:

    const array = [1,2,3,4,5];
    
    // Remove first element
    console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
    // Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
    
    // array = [ 2, 3, 4, 5]
    // Remove last element (start -> array.length+start = 3)
    console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
    // Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]

    More examples in MDN Splice examples


    Slice - MDN reference - ECMA-262 spec

    Syntax
    array.slice([begin[, end]])
    Parameters

    • begin: optional. Initial index (default 0).
      If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array.
    • end: optional. Last index for extraction but not including (default array.length). If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array.

    Returns: An array containing the extracted elements.

    Mutate original: No

    Examples:

    const array = [1,2,3,4,5];
    
    // Extract first element
    console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
    // Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
    
    // Extract last element (start -> array.length+start = 4)
    console.log('Elements extracted:', array.slice(-1), 'array:', array);
    // Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]

    More examples in MDN Slice examples

    Performance comparison

    Don't take this as absolute truth as depending on each scenario one might be performant than the other.
    Performance test

提交回复
热议问题