forEach() fails when using return and appears undefined

When using the forEach() method, you want the callback function to return value*2 and find that it displays undefined.
Or you want to terminate the traversal when a certain condition is reached.

Insert image description here

Insert image description here

The forEach() method calls a function (callback function) once for each array element.
Reason:
forEach has no return value and only calls func for each element.
forEach() cannot terminate the traversal before all elements have been traversed, or return to jump out of the current loop.
In this case, using return will be invalid, and the empty loop will display undefined

Solution:
1. Set a variable and perform various operations on value within the function
Insert image description here
2. Use a for loop (omitted)

3. Use some()/every()
some() to return true as long as one is satisfied, otherwise return false
some(): jump out of the entire loop when true is returned internally

Insert image description here

Insert image description here
This true is returned by some() and is overall

every(): jump out of the entire loop when the internal return false is

every() returns true if every condition is satisfied, otherwise it returns false

If it is detected that one element in the array is not satisfied, the entire expression returns false and the remaining elements will not be tested again.
Returns true if all elements meet the condition.
Insert image description here

Insert image description here

Reference: https://blog.csdn.net/lihefei_coder/article/details/76736296

Guess you like

Origin blog.csdn.net/zhangaob/article/details/108444760