Home >Web Front-end >JS Tutorial >Problems that occur when deleting the contents of array elements in a for loop in JavaScript
The problem that occurred yesterday when using a for loop to deduplicate an array,
First, use a double for loop to compare the previous element with all the following elements, and delete them if they are equal.
However, if there are more than three consecutive equal elements in the array, problems will arise.
var arr = [1,1,1,2,2]; for(var i=0; i<arr.length-1; i++){ for(var j=i+1; j<arr.length; j++){ if(arr[i] === arr[j]){ arr.splice(j,1); } } } document.write("arr:"+arr);
Output:
This is because when an element is deleted from the array, the length of the array is reduced by 1, and the subsequent elements will be moved forward by one, and the index is also reduced by 1, but j still proceeds. The operation of j++.
That is, when deleting for the first time, i=0 j=1, after deletion arr=[1,1,2,2], and then j=2, the element with j=1 after deletion will be ignored and continue. Traverse.
So every time deletion is performed, j must be reduced by 1
var arr = [1,1,1,2,2]; for(var i=0; i<arr.length-1; i++){ for(var j=i+1; j<arr.length; j++){ if(arr[i] == arr[j]){ arr.splice(j--,1); } } } document.write("arr:"+arr);
Output:
Similarly to deleting array elements, it must be considered that the array length will be reduced by 1 , the following elements will be moved forward by one