Solve the deletion of elements by the array splice method in JavaScript to be skipped or only delete some elements

1. Description of the problem

For array traversal, use the splice method to remove eligible elements. Because the splice method changes the length of the original array, but i in the loop still reads the length of the original array, resulting in skipping or only deleting some elements in the array that meet the conditions.

Demo

const studentList = [
  {
    
     name: 'Tom', grade: 55 },
  {
    
     name: 'Jane', grade: 59 },
  {
    
     name: 'Murphy', grade: 80 }
]

for(let i = 0; i < studentList.length; i++) {
    
    
  if (studentList[i].grade < 60) {
    
    
    studentList.splice(i, 1)
  }
}

print result

2. Scheme 1

Real-time synchronous indexing method. For array traversal, when the splice method is executed on the elements that meet the conditions, i--the operation to synchronize the read index with the array after splice.

Demo

const studentList = [
  {
    
     name: 'Tom', grade: 55 },
  {
    
     name: 'Jane', grade: 59 },
  {
    
     name: 'Murphy', grade: 80 }
]

for(let i = 0; i < studentList.length; i++) {
    
    
  if (studentList[i].grade < 60) {
    
    
    studentList.splice(i, 1)
    i--
  }
}

print result

3. Scheme 2

Reverse order traversal method. Because the splice method will directly operate the original array, the width of the array will become smaller, and the following elements will be pushed forward. Therefore, reading from the back to the front, no matter whether the deletion condition is met or not, the correct array item value is read in each loop.

Demo

const studentList = [
  {
    
     name: 'Tom', grade: 55 },
  {
    
     name: 'Jane', grade: 59 },
  {
    
     name: 'Murphy', grade: 80 }
]

for(let i = studentList.length - 1; i >= 0; i--) {
    
    
  if (studentList[i].grade < 60) {
    
    
    studentList.splice(i, 1)
  }
}

print result

4. Scheme 3

filter instead. Unlike the splice method, the filter method does not change the original array, but forms a new array of elements that meet the conditions and returns it.

Demo

const studentList = [
  {
    
     name: 'Tom', grade: 55 },
  {
    
     name: 'Jane', grade: 59 },
  {
    
     name: 'Murphy', grade: 80 }
]

const goodStudentList = studentList.filter(student => {
    
    
  return student.grade > 60
})

print result

Guess you like

Origin blog.csdn.net/qq_41548644/article/details/120711060