JavaScript can not jump out of the forEach loop, know the result, but what caused it?

the forEach cycle is used in the project development process, but the following phenomena are not noticed in the usual use process:

   

Apr.20,2021

  1. ForEach (callback) this is a callback method. You return false doesn't make any sense. If you want to stop, you can use for of .
  2. actually executed three callbacks, but you didn't print the third time in Loop 1.

forEach does not jump out of the loop when the condition is met.

The output statement of

Loop one is after return false

The output statement of

loop 2 is in front of return false, so it creates this illusion.

actually you should use some () or every ();


forEach cannot be interrupted break or return false when traversing an array. You can use for of instead of
to post a detailed article by teacher Zhang Xinxu here. Take a look at

return; here. regardless of whether or not the contains value is added, it can be seen as ending this callback function, so if the traversal is not finished, it will move on to the next callback. And it doesn't stop the for loop. It tastes a bit like continue ?

Menu