Home >Web Front-end >Front-end Q&A >javascript loop delete

javascript loop delete

WBOY
WBOYOriginal
2023-05-17 18:41:384233browse

JavaScript is a very popular programming language with a wide range of applications. During the development process, we often need to process data, which involves looping over arrays and objects. In actual development, sometimes it is necessary to delete certain elements in an array or object. So how to delete these elements in a loop? This article will introduce the loop deletion method in JavaScript and its precautions.

1. Deleting array elements in a for loop

The simplest way to delete array elements in JavaScript is to use a for loop to traverse the array and delete the corresponding elements.

Let’s look at an example first:

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 2 || arr[i] === 4) {
    arr.splice(i, 1);
    i--;
  }
}

console.log(arr); // [1, 3, 5]

In the above code, we use a for loop to traverse the array arr and determine whether the current element is 2 or 4. If so, call arr The .splice(i, 1) method deletes the element and decrements the loop variable i by 1 to ensure that subsequent elements will not be missed. The running results are as follows:

[1, 3, 5]

This method is feasible, but there is a significant problem: each time an element is deleted, the index of the entire array needs to be readjusted, resulting in poor performance. When the number of array elements is large, loop deletion will be very time-consuming. If you only want to delete a small number of elements, you can use this method. However, when removing a large number of elements, other methods are recommended.

2. Deleting array elements in reverse for loop

In addition to using the traditional for loop, you can also use the reverse for loop to delete array elements. Compared with the forward for loop, using the reverse for loop can effectively solve the problem of index rearrangement and improve performance.

For example, to delete even numbers in an array, you can use the following code:

const arr = [1, 2, 3, 4, 5];

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i] % 2 === 0) {
    arr.splice(i, 1);
  }
}

console.log(arr); // [1, 3, 5]

The implementation of this method is basically the same, except that the loop direction is opposite. First start from the array length-1 index and gradually reduce the index value to access the array. Using this method can avoid incremental displacement of the array and improve code efficiency.

3. Use the filter method to delete array elements

Using the ES6 filter method, you can also easily delete array elements. The filter function returns a new array that meets the conditions without changing the original array.

For example, to delete even numbers in an array, the code is as follows:

const arr = [1, 2, 3, 4, 5];

// 返回所有奇数
arr = arr.filter(item => item % 2 !== 0);

console.log(arr); // [1, 3, 5]

This method uses the arrow function in ES6 to determine whether the value of each element is an odd number. If so, retain the elements into the new array. After deleting the even elements, the new array is the result we need.

It should be noted that the filter method will return a new array without modifying the original array. If you need to modify the original array, you can assign this method to the original array.

4. Use the forEach method to delete array elements

In addition to the filter method, you can also use the forEach method to delete array elements. The main idea of ​​this method is to delete elements that do not meet the conditions from the array after traversing the array.

For example, delete the even elements in the array:

let arr = [1, 2, 3, 4, 5];

arr.forEach((item, index) => {
  if (item % 2 === 0) {
    arr.splice(index, 1);
  }
});

console.log(arr); // [1, 3, 5]

The above code uses a forEach loop to traverse the array arr. If an odd number is found, the element is retained in the original array, otherwise the element is deleted. It should be noted that after deleting elements in the loop, the length and index of the array will change, which may cause some elements to be missed. Therefore, it is recommended that when using this method, you first back up the array to avoid unpredictable errors.

5. Precautions

When deleting array elements in a loop, different methods have different scopes of application and precautions. During development, it is necessary to choose an appropriate method based on the actual situation.

  1. If you only delete a small number of elements, you can use the traditional for loop or reverse for loop method, but you need to pay attention to the problem of re-adjusting the index after deletion.
  2. If the number of elements to be deleted is large, you can use the filter method or the forEach method, but it should be noted that after deleting elements in the loop, the length and index of the original array may change, thus affecting subsequent traversals.
  3. When deleting array elements, it is recommended to back up the array to avoid unpredictable errors.
  4. When deleting elements in a for loop, you need to traverse from back to front, otherwise some elements will be missed.

In general, deleting array elements in a loop is a basic skill in JavaScript development. Mastering it will make the code more efficient and beautiful. Several implementation methods are introduced above, and you need to choose based on the actual situation when using them.

The above is the detailed content of javascript loop delete. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:ie8 page jump javascriptNext article:ie8 page jump javascript