Source
Both map
and reduce
have as input the array and a function you define. They are in some way complementary: map
cannot return one single element for an array of multiple elements, while reduce
will always return the accumulator you eventually changed.
map
Using map
you iterate the elements, and for each element you return an element you want.
For example, if you have an array of numbers and want to get their squares, you can do this:
// A function which calculates the square
const square = x => x * x
// Use `map` to get the square of each number
console.log([1, 2, 3, 4, 5].map(square))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…