Home  >  Article  >  Web Front-end  >  Problems that occur when deleting the contents of array elements in a for loop in JavaScript

Problems that occur when deleting the contents of array elements in a for loop in JavaScript

高洛峰
高洛峰Original
2016-12-06 13:13:211305browse

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:

Problems that occur when deleting the contents of array elements in a for loop in JavaScript

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:

Problems that occur when deleting the contents of array elements in a for loop in JavaScript

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


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