When it comes to array collapse, let’s look at a picture.
If an element in the array is deleted, the current index will not be empty and will not occupy space. The array will only fill in the following elements, which will cause the original index of the following elements to change. This phenomenon is called array collapse.
Case analysis
Let’s take a look at the distress caused by array collapse.
In a nutshell, we store four functions fn1, fn2, fn3, and fn4 in an array arr, printing 1, 2, 3, and 4 respectively, while the second function internally deletes the first element fn1 in the array.
When we execute obj.fire(), we execute all four functions in the array one by one, but because of the collapse of the array, we delete the first element when we execute the second function (I = 1).
This causes the index of all subsequent elements to be reduced by one, and the I = 2 after that is no longer fn3, but the last element fn4, so it will only print 1, 2, and 4.
The solution
When we know why the array collapsed, we should not delete the element directly. Instead, we should replace the current element with NULL. When iterating through the array a second time, filter out elements that are null.
Once you understand array collapse, familiarize yourself with the publish-subscribe model so that you don’t fall into the trap of the event center, you can avoid errors in event scheduling.