答案 0 :(得分:1)
您可以运行从19-i
到0
的循环,而当i
进一步增加时,19-i
的值会越来越小:
var out = document.getElementById("out");
for (var i = 0; i < 20; i++ ){
if ( i <= 10){
for ( var j = 0; j < i; j++ ){
out.innerHTML += "*";
}
} else if (i > 10){
for ( var j = 19-i; j >= 0; j--){ // <-- run loop so that number of iterations gets lower and lower
out.innerHTML += "*";
}
}
out.innerHTML += "<br>";
}
<p id="out"></p>
答案 1 :(得分:0)
基于给定步骤/
计数Pyramid
形状的简单解决方案:
var steps = 5, outputStr = "", isTriangle = false;
var newLine = "<br />"; // "\n" for String, <br /> for element break line.
for (var i = 1; i <= steps; i++) {
// Forward
for (var j = 1; j <= i; j++) {
outputStr += i;
}
outputStr += newLine;
if (i == steps && !isTriangle) {
// Backward - After completing Forward
var k = i - 1;
while (k > 0) {
for (var j = k; j > 0; j--) {
outputStr += k;
}
k--;
outputStr += newLine;
}
}
}
var out = document.getElementById("out");
out.innerHTML = outputStr;
<p id="out"></p>
对于Java,请参见:Draw Pyramid