current position:Home>Difference between front-end foreach and map

Difference between front-end foreach and map

2022-06-24 09:43:26You are far from it.

I have always wanted to write about the difference between the two , Reading what others have written on the Internet is not very comprehensive .
1. map

It doesn't change the original array
Yes return Return value

2.forEach

No, return
Interrupts throw Error

Normal return

 		[1, 2, 3, 4, 5].forEach((v) => {
    
            if (v == 3) {
    
                return
            }
            console.log(v);
        })

 Insert picture description here

Use if we need to interrupt try catch To capture error messages

 try {
    
            [1, 2, 3, 4, 5].forEach((v) => {
    
                if (v == 3) {
    
                    throw Error(' Interrupt success ')
                }
                console.log(v);
            })
        } catch (error) {
    
            console.log(error, ' It's broken ');

        }

 Insert picture description here
About try catch
Be similar to promise then catch
In the following cases

1.forEach interrupt
2. Upload files Failed callback
3. Network request

copyright notice
author[You are far from it.],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240824353759.html

Random recommended