SoFunction
Updated on 2025-04-07

Splice method in JS array and sharing using native writing method

1. What is splice

The splice() method is used to add and delete the array. This method returns the deleted elements and changes the original array.

2. The splice() method accepts three or more parameters:

  • The first parameter: The first parameter is the starting position (the index of the array)
  • The second parameter: The second parameter is the number of elements to be deleted. If the parameter is a negative number, the default is 0.
  • The third and subsequent parameters: These parameters are the parameters to be added to the array

3. Parameter introduction

1. If the first parameter is a positive number, delete all subsequent elements including themselves starting from index 1.

let arr = [1, 2, 3, 4, 5]
let newArr = (1) // Start deleting all subsequent elements including themselves from index 1(arr) // [1]
(newArr) // [2, 3, 4, 5]

If the first parameter is greater than the maximum index value, an empty array is returned

let arr = [1, 2, 3, 4, 5]
let newArr = (5) // Greater than the maximum index value (4)(arr) // [1, 2, 3, 4, 5]
(newArr) // []

If the first parameter is a negative number, the number of elements deleted from the end of the array is the parameter value

let arr = [1, 2, 3, 4, 5]
let newArr = (-2) // Remove 2 elements from the end of the array(arr) // [1, 2, 3]
(newArr) // [4, 5]

If the first parameter is a negative number and the absolute value of the negative number is less than or equal to the length of the array

let arr = [1, 2, 3, 4, 5]
let newArr = (-5) // The absolute value of this parameter is less than or equal to the length of the array(arr) // []
(newArr) // [1, 2, 3, 4, 5]

4. When there are two parameters

The first parameter is the starting position, the second parameter is the number of elements to be deleted. If the second parameter is negative, the default is 0

 let arr = [1, 2, 3, 4, 5]
let newArr = (2, 2) // Two parameters The starting value starts from index 0. Here the starting value is 3. Delete two elements including themselves(arr) // [1,2,5]
(newArr) // [3, 4]
 
let arr1 = [1, 2, 3, 4, 5]
let newArr1 = (-2, 2) // Start from the end of the array to calculate the starting value to 3 in the array elements. Delete two elements including themselves.(arr1) // [1,2,3]
(newArr1) // [4, 5]

5. Native JS handwritten splice() method

Ideas

1. When there is only one parameter, determine the special and normal situations of the parameter.

Special circumstances:

(1). When the value of the parameter is undefined, then the parameter is directly assigned to 0 (2). When the value of the parameter is larger than the index value of the last element of the array, then a blank array is directly returned (3). When the parameter is 0, or the absolute value of the parameter is larger than the length of the array or the passed in is not a number, then the value is assigned to the final return array, and the length of the original array is set to 0

Normal situation:

1. This parameter is a reasonable positive number and a reasonable negative number. Then, assign a value to the new array through a for loop to reduce the length of the original array.

2. When there are two parameters, first determine whether the second parameter is reasonable, or it is a negative number or not a number to convert it to 0.

Call a custom method, pass the first parameter in to obtain all deleted elements, and intercept the number of deleted second parameter through the slice method.

3. When there are three or more parameters, a starting position start is obtained by judging the first parameter.

If the first parameter is a negative number and its absolute value is greater than the length of the original array, then the starting position is 0. Otherwise, the length of the original array plus the first parameter. If the first parameter is a positive number and is within the range of the last element index of the array, then the starting position is the first parameter

Call the custom method, pass the first two parameters in, and get the deleted elements, and use (middle). At this time, this (original array) is the remaining elements. Assign left to the last array to be returned. Clear the middle and push the third and above parameters into the middle. This way, an array composed of new elements is obtained. At this time, the original array is the remaining parameters. Intercept this from the starting position to obtain the end array. When the elements before the starting position of this are deleted, you will get the head (this), the middle part (middle), the right (end), and then push the middle part and the right part into this to get a new array after changing.

  = function () {
        // The final new array returned        let newArr = []
        // A parameter        if ( === 1) {
          // If the first parameter is passed in undefined or null, the value is directly assigned to 0          if (arguments[0] === undefined) {
            arguments[0] = 0
          }
          // If the first parameter is larger than the last index of the array, then none of them will be deleted. Return to the empty array directly          if (arguments[0] >  - 1) {
            return newArr
          }
          // If the first parameter is negative, the number is smaller than the negative value of the original array. The first parameter is 0. The first parameter is passed in is not a number.          if (arguments[0] <= - || arguments[0] == 0 || typeof arguments[0] === 'string') {
            // Assign newArr value            newArr = [...this]
            // Clear the original array             = 0
            return newArr
          }
          // If it is a reasonable negative number          if (arguments[0] < 0 && arguments[0] > -) {
            // Turn to positive number            arguments[0] *= -1
            // traverse the starting position of the first parameter            for (let i = 0; i < arguments[0]; i++) {
              // From item 0 to newArr              newArr[i] = this[ - arguments[0] + i]
            }
            // If the first parameter is negative, it is to delete the element of the first parameter value from the end of the array.             -= arguments[0]
            return newArr
          }
          // If it is a positive number and within a reasonable range          if (arguments[0] > 0 && arguments[0] <=  - 1) {
            for (let i =  - 1; i > arguments[0] - 1; i--) {
              // Assign deleted elements to newArr              newArr[i - arguments[0]] = this[i]
              // Decrease the length of the array by 1 per loop              --
            }
            return newArr
          }
        }
 
        // Two parameters        if ( === 2) {
          // The second parameter is negative and defaults to 0. It is a string. It is undefined or null.          if (arguments[1] < 0 || typeof arguments[1] === 'string' || arguments[1] === undefined) {
            arguments[1] = 0
          }
          // Delete part If there is only one parameter, get the deleted part          let deletePart = (arguments[0])
 
          // The remaining elements that do not need to be deleted from the appropriate location          let residue = (arguments[1])
 
          // Switch out the deleted elements into a new array Starting from 0          let newArr = (0, arguments[1])
 
          //Travel over the elements that have not been deleted and push into this          for (let i = 0; i < ; i++) {
            (residue[i])
          }
          return newArr
        }
 
        // Three parameters and more        if ( >= 3) {
          // Define where to start deletion          let start = null
          // If the first parameter is smaller than the negative length of the original array, then the value is 0          if (arguments[0] <= -) {
            arguments[0] = 0
            start = 0
          } else {
            // The starting value after converting to a positive number: Example start = 6 + -1            start =  + arguments[0]
          }
          // Start value in the range of valid positive numbers          if (arguments[0] >= 0 && arguments[0] < ) {
            start = arguments[0]
          }
          // Get the deleted element arr = [1, 2, 3, 4, 5, 6] (3,2,0,0)          let result = (arguments[0], arguments[1]) // resulte:[5,6]
          // Intercept the deleted element          let newArr = (0, arguments[1]) // Get the return value newArr:[5,6]          // Put the element you want to add into the deleted element group          for (let i = 2; i < ; i++) {
            (arguments[i]) // resulte:[5,6,0,0]
          }
          // Delete the deleted elements. The rest are the elements that need to be added          for (let i = 0; i < ; i++) {
            (arguments[i]) // results:[0,0]
          }
 
          // start:3   this:[1,2,3,4]
          let end = (start === 0 ? arguments[1] : start) // end:[6]
 
          if (start === 0) {
            for (let i = 0; i < ; i++) {
              (result[i])
            }
          } else {
            for (let i = 0; i < ; i++) {
              () // this:[1,2,3]
            }
            for (let i = 0; i < ; i++) {
              (result[i]) // this:[1,2,3,0,0]
            }
            for (let i = 0; i < ; i++) {
              (end[i]) // this:[1,2,3,0,0,6]
            }
          }
          return newArr
        }
      }

6. Detailed explanation of splice() in js (insert, delete or replace elements of array)

There are many ways to deal with arrays. JavaScript's splice() is the most powerful. It can be used to insert, delete or replace elements of an array.

delete: Used to delete elements, two parameters, the first parameter (the position of the first item to be deleted), and the second parameter (the number of items to be deleted)

Remove 1 element from index 3
var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"];
var removed = (3, 1);

// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "surgeon"]

insert: Insert any item element to the specified position of the array. Three parameters, the first parameter (actual position), the second parameter (0), and the third parameter (inserted item)

Remove 0 elements from index 2, and insert "drum"
var myFish = ["angel", "clown", "mandarin", "surgeon"];
var removed = (2, 0, "drum");

// myFish is ["angel", "clown", "drum", "mandarin", "surgeon"] 
// removed is [], no elements removed

replace: Insert any item element into the specified position of the array, and delete any number of items at the same time, three parameters. The first parameter (start position), the second parameter (number of items deleted), and the third parameter (insert any number of items)

Remove 1 element from index 2, and insert "trumpet"
var myFish = ["angel", "clown", "drum", "surgeon"];
var removed = (2, 1, 'trumpet');

// myFish is ["angel", "clown", "trumpet", "surgeon"]
// removed is ["drum"]

This is the article about the splice() method in JS array and the sharing of native writing methods. For more information about JS splice() usage introduction, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!