Книга: Functional Programming in JavaScript
Назад: Callbacks
Дальше: Array.prototype.filter()

Array.prototype.map()

The function is the ringleader of the bunch. It simply applies the callback function on each item in the array.

Note

Syntax:

Parameters:

  • : This function produces an element for the new array, receiving these arguments:
    • : This argument gives the current element being processed in the array
    • : This argument gives the index of the current element in the array
    • : This argument gives the array being processed
  • : This function is optional. The value is used as when executing .

Examples:

var   integers = [1,-0,9,-8,3],   numbers = [1,2,3,4],   str = 'hello world how ya doing?'; // map integers to their absolute values console.log(integers.map(Math.abs));  // multiply an array of numbers by their position in the array console.log(numbers.map(function(x, i){return x*i}) );  // Capitalize every other word in a string. console.log(str.split(' ').map(function(s, i){   if (i%2 == 0) {     return s.toUpperCase();   }   else {     return s;   } }) );

Note

While the method is a standard method for the Array object in JavaScript, it can be easily extended to your custom objects as well.

MyObject.prototype.map = function(f) {   return new MyObject(f(this.value)); };
Назад: Callbacks
Дальше: Array.prototype.filter()

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)