The map() function of array object creates a new array with the results of calling a provided function on every element in this array. Use it for example to perform some operation on each element of array and create new array.
Syntax
arr.map(callback[, thisArg])
<html>
<head>
<script type="text/javascript">
var array = [1, 4, 9];
var newArray = array.map(Math.sqrt);
document.write(newArray[0] + ' ' + newArray[1] + ' ' + newArray[2]);
</script>
</head>
<body>
</body>
</html>
This will produce following result
1 2 3
<html>
<head>
<script type="text/javascript">
// Create an array.
var arr = [1,2,3];
var newArray = arr.map(function(num) {
return num * 2;
});
document.write(newArray[0] + ' ' + newArray[1] + ' ' + newArray[2]);
</script>
</head>
<body>
</body>
</html>
This will produce following result
2 4 6
<html>
<head>
<script type="text/javascript">
// Create an array.
var arr = [1,2,3];
// Define the callback function.
function AreaOfCircle(radius) {
var area = Math.PI * (radius * radius);
return area.toFixed(0);
}
// Get the areas from the radii.
var areas = arr.map(AreaOfCircle);
document.write(areas);
</script>
</head>
<body>
</body>
</html>
This will produce following result
3,13,28