Working on exercises from a manual that required printing array items into list elements.
Here is the code provided:
<!doctype html>
<html lang="en>
<head>
<title>Temperatures</title>
<meta charset="utf-8">
<script>
function showTemps() {
var tempByHour = new Array();
tempByHour[0] = 59.2;
tempByHour[1] = 60.1;
tempByHour[2] = 63;
tempByHour[3] = 65;
tempByHour[4] = 62;
for (var i = 0; i < tempByHour.length; i++) {
var theTemp = tempByHour[i];
var id = "temp" + i;
var li = document.getElementById(id);
if (i == 0) {
li.innerHTML = "The temperature at noon was " + theTemp;
} else {
li.innerHTML = "The temperature at " + [i] + " was " + theTemp;
}
}
}
window.onload = showTemps;
</script>
</head>
<body>
<h1>Temperatures</h1>
<ul>
<li id="temp0"></li>
<li id="temp1"></li>
<li id="temp2"></li>
<li id="temp3"></li>
<li id="temp4"></li>
</ul>
</body>
</html>
I initially attempted to create my own solution using a for loop and the createElement method, but unfortunately it did not work as expected.
var messageGen = function() {
var forecastByHour = [32, 15, 19, 25, 21];
for (var i =0; i <= forecastByHour.length; i++) {
var temp = forecastByHour[i];
var message = "On the " + [i] + " hour the expected forecast is" + temp;
var listItems = document.createElement("li");
listItems.innerHTML = message
}
}
Does anyone have an easier solution for this task?