How to map Javascript array value

Description

map() accepts two arguments:

  • a function to run on each item and
  • an optional scope object

map() runs the given function on every item and returns the result of each function call in an array.

The function passed in receives three arguments:

  • the array item value,
  • the position of the item in the array
  • the array object itself.

Example

The following code uses map() to double each value in array.


var numbers = [1,2,3,4,5,4,3,2,1]; 
        /*from www  .  j  a v  a  2  s  .co m*/
var mapResult = numbers.map(function(item, index, array){ 
   return item * 2; 
}); 
console.log(mapResult); 

The code above generates the following result.

map() does not change the values contained in the array.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window