In the recent process of learning and using ES6, when looping through an array and making a judgment, the return value is invalid, and the result returned is undefined
We use for loop and forEach method respectively to verify:
Result: The return in the for loop can terminate the traversal, but the return in forEach cannot terminate the traversal
The above is return to terminate the traversal of the for loop and the traversal test of the forEach loop.
————————————————– ————— Dividing line——————————— —————————————-
What I originally wanted to achieve was to get a value and return it by judging the condition. Let’s take a look at the effect first
The printing result is as shown below:
Obviously: Array’s forEach() method cannot return.
My solution is: define a variable, save the value I want to return, and finally return it (the best method will be added)
Console print results:
As shown in the figure, I successfully obtained the number that meets the judgment conditions
Technical summary: forEach cannot terminate the traversal before all elements are passed to the called function / return in the forEach method is invalid
The above is the entire content of this article. I hope it will be helpful to everyone’s study and I hope you will support me a lot.