What is the difference between .map, .every, and .forEach?

前端 未结 4 1373
遥遥无期
遥遥无期 2020-12-04 05:26

I\'ve always wondered what the difference between them were. They all seem to do the same thing...

4条回答
  •  不知归路
    2020-12-04 05:41

    gilly3's answer is great. I just wanted to add a bit of information about other types of "loop through elements" functions.

    • .every() (stops looping the first time the iterator returns false or something falsey)
    • .some() (stops looping the first time the iterator returns true or something truthy)
    • .filter() (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
    • .map() (creates a new array from the values returned by the iterator function)
    • .reduce() (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
    • .reduceRight() (like reduce, but works in descending rather than ascending order)

    credit to: T.J.Crowder For-each over an array in JavaScript?

提交回复
热议问题