what use does the javascript forEach method have (that map can't do)?

前端 未结 8 1450
小鲜肉
小鲜肉 2020-12-04 07:24

The only difference I see in map and foreach is that map is returning an array and forEach is not. However, I don\'t even understand the last line

8条回答
  •  青春惊慌失措
    2020-12-04 07:42

    Once again, I feel like a necromancer adding a response to a question that has been asked 5 years ago (happily there is rather recent activity, so I am not the only one disturbing the dead:).

    Others have already posted about your main question regarding the difference between the functions. But for...

    are there any real uses for these methods in javascript (since we aren't updating a database) other than to manipulate numbers like this:

    ...it's funny you should ask. Just today I wrote a piece of code that assigns a number of values from a regular expression to multiple variables using map for transformation. It was used to convert a very complicated text based structure into visualizeable data ... but for simplicity's sake, I shall offer an example using date strings, because those are probably more familiar for everyone (though, if my problem had actually been with dates, instead of map I would've used Date-object, which would've done the job splendidly on its own).

    const DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
    const TEST_STRING = '2016-01-04T03:20:00.000Z';
    
    var [
        iYear,
        iMonth,
        iDay,
        iHour,
        iMinute,
        iSecond,
        iMillisecond
        ] = DATE_REGEXP
            // We take our regular expression and...
            .exec(TEST_STRING)
            // ...execute it against our string (resulting in an array of matches)...
            .slice(1)
            // ...drop the 0th element from those (which is the "full string match")...
            .map(value => parseInt(value, 10));
            // ...and map the rest of the values to integers...
    
    // ...which we now have as individual variables at our perusal
    console.debug('RESULT =>', iYear, iMonth, iDay, iHour, iMinute, iSecond, iMillisecond);
    

    So ... while this was just an example - and only did a very basic transformation for the data (just for sake of example) ... having done this without map would've been a much more tedious task.

    Granted, it is written in a version of JavaScript that I don't think too many browsers support yet (at least fully) but - we're getting there. If I needed to run it in browser, I believe it would transpile nicely.

提交回复
热议问题