1024programmer Java Solution to return failure problem in JavaScriptforEach

Solution to return failure problem in JavaScriptforEach

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.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/697314

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top