JavaScript Array map() Method

Array 对象参考手册JavaScript Array Object

Example

Return an array, whose elements are the square roots of the original array elements:

var numbers = [4, 9, 16, 25];

function myFunction() {
    x = document.getElementById("demo")
    x.innerHTML = numbers.map(Math.sqrt);
}

The output result is:

2,3,4,5

Try it Yourself »

Definition and Usage

The map() method returns a new array, whose elements are the values obtained by calling a function on the original array elements.

The map() method processes elements in order according to the original array element order.

Note:map() does not check empty arrays.

Note:map() does not change the original array.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
map() Yes 9 1.5 Yes Yes

Syntax

array.map(function(currentValue,index,arr), thisValue)

Parameter Details

Parameter Description
function(currentValue, index,arr) Required. A function that will be executed for each element in the array.
Function parameters:
Parameter Description
currentValue Required. The value of the current element.
index Optional. The index of the current element.
arr Optional. The array object the current element belongs to.
thisValue Optional. An object to use as "this" when executing the callback, passed to the function.
If thisValue is omitted, or if null or undefined is passed, the callback function's this will be the global object.

Technical Details

Return value: Returns a new array, whose elements are the values obtained by calling a function on the original array elements.
JavaScript Version: 1.6

More Examples

Example

Multiply each element in the array by the value specified in the input field, and return a new array:

var numbers = [65, 44, 12, 4];

function multiplyArrayElement(num) {
    return num * document.getElementById("multiplyWith").value;
}

function myFunction() {
    document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}

Try it Yourself »

Array 对象参考手册JavaScript Array Object

Other Extensions