Saturday, April 26, 2014

Javascript example: access all elements in array using forEach()

Javascript example to access all elements in array using forEach().

<!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 = [1, 'a', 'BCD', 3.1416];

    document.getElementById("p1").innerHTML=array;
    
    var resultDiv = document.getElementById("resultdiv");
    
    array.forEach(
        function(element, index){
            var newP = document.createElement("p");
            newP.innerHTML = index + " : " + element + " : " + typeof(element);
            resultDiv.appendChild(newP);
        }
    );
}
 
</script>
</body>
</html>


No comments:

Post a Comment