Example of several methods for deleting elements in an array in Javascript loop: javascript Array
This article mainly shares with you several methods to delete elements in an array through Javascript loop, for your reference and learning. The following is a detailed introduction:
Problems Found
You may need to remove a specified element in a loop during code execution. According to the general idea, a for loop is used directly, and then an if clause is used in the loop to determine whether to delete the specified element. However, the actual situation is often not as smooth as expected.
The following uses a piece of Javascript code as an example to demonstrate this process.
(Function () {var arr = [1, 2, 3, 4, 5]; var len = arr. length; for (var I = 0; I <len; I ++) {// print the conditions in the array for easy tracking of data changes in the array console. log (I + "=" + arr [I]); // delete all elements with 2 if (arr [I] = 2) {arr. splice (I, 1) ;}} console. log (arr );})();
The running result is as follows:
The final result shows that only one matching element is deleted, and another element exists.
It is not difficult to find out from the printed running process because the index of the array changes after an element is deleted, resulting in program exceptions.
Solution
It is not difficult to solve the problem after finding the cause of the problem.
Method 1
(Function () {var arr = [1, 2, 3, 4, 5]; var len = arr. length; for (var I = 0; I <len; I ++) {// print the conditions in the array for easy tracking of data changes in the array console. log (I + "=" + arr [I]); // delete all elements that have 2 if (arr [I] = 2) {// compare this line of code: Delete the element and adjust the value of arr. splice (I --, 1) ;}} console. log (arr );})();
The above Code does not seem to be easy to understand. Is there any code that looks easier to understand? See the following
Method 2
(function () { var arr = [1,2,2,3,4,5]; var len = arr.length-1; //start from the top for(var i=len;i>=0;i--){ console.log(i+"="+arr[i]); if(arr[i]==2){ arr.splice(i,1); } } console.log(arr);})();
Traversing from the back can effectively solve the problem and be easy to understand. Is there any concise implementation? Next, let's look at the following code:
Method 3
(function () { var arr = [1,2,2,3,4,5]; var i = arr.length; while(i--){ console.log(i+"="+arr[i]); if(arr[i]==2){ arr.splice(i,1); } } console.log(arr);})();
Usewhile(i--)
, I is the array subscript. I personally think this is the most concise and efficient code implementation.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.