Javascript examples for Array:map
The map() method creates a new array with the results of calling a function for every array element.
array.map(function(currentValue, index, arr),thisValue);
Parameter | Description |
---|---|
function(currentValue, index, arr) | Required. A function to be run for each element in the array. |
currentValue | Required. The value of the current element |
index | Optional. The array index of the current element |
arr | Optional. The array object the current element belongs to |
thisValue | Optional. A value to be passed to the function to be used as its "this" value. |
An Array containing the results of calling the provided function for each element in the original array.
The following code shows how to use the map function:
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <p>New array: <span id="demo"></span></p> <script> var persons = [/*from ww w. ja va2 s.c om*/ {firstname : "A", lastname: "R"}, {firstname : "K", lastname: "F"}, {firstname : "J", lastname: "C"} ]; function getFullName(item,index) { var fullname = [item.firstname,item.lastname].join(" "); return fullname; } function myFunction() { document.getElementById("demo").innerHTML = persons.map(getFullName); } </script> </body> </html>