Home >Web Front-end >JS Tutorial >JS reverse order traversal implementation code_javascript skills
The most commonly used traversal method is the for statement (there are also recursive and while methods). When we iterate through an array, we usually do this:
This is the most commonly used traversal method: forward traversal. It goes from the first item to the last item in the array.
Then why does today’s drama also mention reverse order traversal?
Here I have to mention one of the most commonly used modules among the components written in small dramas: events. Used to create custom event models, handle event monitoring and triggering, the simplest publish and subscribe (pub/sub) mode. Because it was recently discovered that there is a hidden danger of memory overflow, it is necessary to add an unbinding method on the original basis.
Because callback functions with the same event name are placed in the same array, to unbind, you only need to find the corresponding callback function in the array (the same callback function may be bound multiple times) and remove it.
It is a very simple requirement, so it is natural to write code similar to the following:
Is there any normal code, but the final output result is: [1, 2, 2, 1, 1, 2]. Obviously the execution result is not as expected.
What’s the problem?
After careful analysis, I found that the problem lies in that every time the match is successful, after the removal operation is performed, the next item to be checked will be skipped, because each subsequent item in the array moves forward by one.
I found the problem, changed the code, and adjusted the sequence index index (i) after performing the removal operation.
The problem is solved, but I still feel that modifying the sequence index is a tease of the for loop. Then I had a flash of inspiration, bang bang bang, and typed out the following code:
The traversal process remains unchanged, the only change is that the order of traversal has changed, and by the way, there is one less variable total.
Okay, I admit that what I wrote today is very silly, but through this example, I will remind you when writing code in the future. During the traversal process, if it involves modifying the array itself (addition and deletion), reverse traversal is a comparison Safe way to traverse.
Coding notes, leave them to laugh at yourself later!
Please indicate the source when reprinting: http://bh-lay.com/blog/148c07761fa