The map()
method creates a new array with the results of calling a function for every array element and calls the provided function once for each element in an array, in order.
map()
does not execute the function for array elements without values.
Syntax and Usage
array.map(function(currentValue, index, arr), thisValue)
Parameter Values
function(currentValue, index, arr) -> Required. A function to be run for each element in the array.
Function arguments:
Argument Description
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.
If this parameter is empty, the value "undefined" will be passed as its "this" value
Let's start
Example(1)
1.Create array elements
var numbers = [4, 2,6];
2.Impement code to do factorail for above array elements.
function myFunction() {
var newarray = numbers.map(Factorial)//calling factorial for each element
function Factorial(n) {
var ans=1;
for (var i = 2; i <= n; i++)
ans = ans * i;
return ans;
}
document.getElementById("demo").innerHTML = newarray;
Complete code for map function in java script
<!DOCTYPE html>
<html>
<head>
<title>How To Use Array map Function In JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br>
<br>
<div class="text-center">
<h1>Array map() Function In JavaScript</h1>
</div>
<br>
<div class="well">
<button class="btn btn-primary" onclick="myFunction()">Click it</button>
<h1 id="demo"></h1>
</div>
<br>
</div>
</body>
</html>
<script>
var numbers = [4,2,6];
function myFunction() {
var newarray = numbers.map(Factorial)//calling factorial for each element
function Factorial(n) {
var ans=1;
for (var i = 2; i <= n; i++)
ans = ans * i;
return ans;
}
document.getElementById("demo").innerHTML = newarray;
}
</script>