I created a pyramid using JavaScript and below is the code that I tried so far using for loop:
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) { //Outer loop
for (var j = 1; j <= i; j++) { //Inner loop
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
Pretty basic! But I am trying to bind the result with HTML element, say with div as follows:
document.getElementById('result').innerHTML = output;
Instead it shows five stars in a row rather than the format in JS seeing in the console. Anything that I am missing here?
Full Code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++) {
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id="result"></div>
</body>