JavaScript Array map() Method
Example
Return an array whose elements are the square roots of the original array:
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 »
Definition and Usage
The map() method returns a new array whose elements are the values of the original array elements after being processed by a function.
The map() method processes elements in the order of the original array elements.
Note: map() does not process empty arrays.
Note: map() does not change the original array.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| map() | Yes | 9 | 1.5 | Yes | Yes |
Syntax
array.map(function(currentValue,index,arr), thisValue)
Parameter Description
| Parameters | Description |
|---|---|
| function(currentValue, index,arr) | Required. A function that is executed for each element in the array |
函数参数:
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 | Parameter | Description | *currentValue* | Required. The value of the current element | *index* | Optional. The index value of the current element | *arr* | Optional. The array object the current element belongs to | | Parameter | Description | | *currentValue* | Required. The value of the current element | | *index* | Optional. The index value of the current element | | *arr* | Optional. The array object the current element belongs to | | *thisValue* | Optional. An object used as the value of "this" when executing the callback, passed to the function. If thisValue is omitted, or null/undefined is passed, the callback's this is the global object.
Technical Details
Return Value:
Returns a new array whose elements are the values of the original array elements after being processed by a function.
JavaScript version:
1.6
More examples
Example
Multiply each element in the array by the value specified in the input box, 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 »
JavaScript Array object