The map in JS, forEach cannot jump out of the loop, the use of every and some

When traversing the array in the project, the use of array.map
needs to be judged in the loop. As long as one item satisfies the condition, it will return false and
find that the effect is wrong. After debugging, it is found that the return does not really exit the loop.

Let's explore the correct jump out of the loop~~

1.map

Using return cannot break out of the loop

  let arr = [1,2,3];
    arr.map((item)=>{
        if(item == 2){
            return false
        }
        console.log(item)
    })

Use break to report an error

 let arr = [1,2,3];
    arr.map((item)=>{
        if(item == 2){
            break;
        }
        console.log(item)
    })

2.forEach

Using return cannot break out of the loop

 let arr = [1,2,3];
    arr.forEach((item)=>{
        if(item == 2){
            return false
        }
        console.log(item)
    })

Use break to report an error

let arr = [1,2,3];
    arr.forEach((item)=>{
        if(item == 2){
          break;
        }
        console.log(item)
    })

 

3. every method 

Determine whether all elements in the array meet the condition

The every() method will traverse each item of the array. If there is an item that does not meet the condition, the expression will return false, and the remaining items will not be tested again; if each item meets the condition after traversing the array, then returns true.

return true : The loop continues if the current element satisfies the condition and continues to judge. If the loop execution is still true, the return value of every is true

return false : the loop ends, the current element does not satisfy the condition, and the return value of every is also false

let arr = [1,2,3];
    arr.every((item)=>{
        if(item == 2){
          return false
        }
        console.log(item)
    })

4.some method 

Determine whether there is an element in the array that satisfies the condition

return true : the loop ends and an element that satisfies the condition is found

return false : the loop continues, the loop continues if it is not found, if all elements are traversed and still not found, the final result is false

let arr = [1,2,3];
    arr.some((item)=>{
        if(item == 2){
          return true
        }
        console.log(item)
    })

 5. The for loop can jump out of the loop using both return and break

Guess you like

Origin blog.csdn.net/m0_49623851/article/details/128487711