Core JavaScript

For Loops on Arrays

This JavaScript example runs four different kinds of for loops over the elements of an array.

ForLoopsOnArrays.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="ForLoopsOnArrays.js"></script>
</body>
</html>

ForLoopsOnArrays.js

var saApostles = ['Peter', 'Andrew', 'James the Great', 'John',
  'Philip', 'Bartholomew', 'Thomas', 'Matthew', 'James',
  'Thaddaeus', 'Simon the Zealot', 'Judas Iscariot'];

// For-Of Loop
document.write("For-Of Loop<br >");
document.write("------------------------------------<br >");
for (var sApostle of saApostles) {
  document.write(sApostle + "<br >");
}

// For-In Loop
document.write("<br >For-In Loop<br >");
document.write("------------------------------------<br >");
for (var xProperty in saApostles) {
  document.write("Property = " + xProperty +
  	" : saApostles[" + xProperty + "] = " + saApostles[xProperty] +
  	"<br >");
}

// For Loop
document.write("<br >For Loop<br >");
document.write("------------------------------------<br >");
for (var i = 0; i < saApostles.length; ++i) {
  document.write("Index = " + i +
  	" : saApostles[" + i + "] = " + saApostles[i] + "<br >");
}

// forEach Loop
function Print(sValue, iIndex, saArray) {
  document.write("Value = " + sValue + " : Index = " + iIndex +
  	" : Array[" + iIndex + "] = " + saArray[iIndex] + "<br >");
}
document.write("<br >forEach Loop<br >");
document.write("------------------------------------<br >");
saApostles.forEach(Print, saApostles);
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.