Array collapse

Array collapse

  • First prepare an array
var arr = [1,2,3,4,5];
  • Traverse the array to delete each element
for(var i=0;i<arr.length;i++){
    
    
	arr.splice(i,1);
	// 0 - [2,3,4,5]
	// 1 - [2,4,5]
	// 2 - [2,4]
	//
}
console.log(arr); // [2,4]
  • The above code failed to delete all the elements in the array, the reason is:
  1. When i=0the time element is deleted ,, 1 arr.length=4,arr[0] = 2,arr[1] = 3
  2. When i=1the time element is deleted ,, 3 arr.length=3,arr[0] = 2,arr[1] = 4,arr[2] = 5
  3. When i=2the time element is deleted ,, 5 arr.length=2,arr[0] = 2,arr[1] = 4
  4. When i=3the time, because before arr.length=2, arr[3]does not exist
  5. This phenomenon is called array collapse .

Solution

  1. Delete backwards
for(var i=arr.length-1; i>=0; i--){
    
    
	arr.splice(i,1);
}
console.log(arr);	// []
  1. Let the variable not increment
for(var i=0; i<arr.length; i++){
    
    
	arr.splice(i,1);
	i--;
}
console.log(arr);	// []
  1. Delete the first element every time
for(var i=0; i<arr.length; i++){
    
    
	arr.splice(0,1);
}
console.log(arr);	// []
  1. Use while loop to delete
while(arr.length){
    
    
	arr.splice(0,1);
}
console.log(arr);	// []

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/114290750