<!DOCTYPE html>
<html>
<body onload="doit();">
<h1>mobile-web-app.blogspot.com</h1>
<p id="p1"></p>
<div id="resultdiv"></div>
<script type="text/javascript">
function doit()
{ var array = [0, 45, 90, 180, 270, 360];
document.getElementById("p1").innerHTML=array;
var resultDiv = document.getElementById("resultdiv");
var array2 = array.map(function(x) {return Math.sin(x * (Math.PI / 180))});
printAll(array2, resultDiv);
var array3 = array.map(cos);
printAll(array3, resultDiv);
}
function cos(x){
return Math.cos(x * (Math.PI / 180));
}
function printAll(arr, container){
arr.forEach(
function(element, index){
var newP = document.createElement("p");
newP.innerHTML = index + " : " + element;
container.appendChild(newP);
}
);
}
</script>
</body>
</html>
Saturday, April 26, 2014
Apply function to array elements to create another array, map()
This example show how to create array by applying function to a existing array, using map().

No comments:
Post a Comment