1 回答

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
我對(duì)您的代碼進(jìn)行了細(xì)微修改。你幾乎擁有它。我會(huì)按原樣重用相同的嵌套 for 循環(huán)。只需更改循環(huán)的頂層。
金字塔的頂端運(yùn)行:
for(var i=1; i<=x;i++)
底部金字塔用于:
for(var i=x-1; i>=1; i--)
您應(yīng)該考慮將重復(fù)的嵌套代碼移動(dòng)到一個(gè)函數(shù)中,并將 的值i作為參數(shù)傳遞給該函數(shù)。
function clicked() {
var x = document.getElementById("num").value;
if (x < 50) {
document.write("Your Number is: " + x + "<br />Your number is lower than 50<br />");
} else if (x > 50) {
document.write("Your Number is: " + x + "<br />Your number is more than50<br />");
} else {
document.write("Your Number is: " + x + "<br />Your number is equal to 50<br />");
}
for (var i = 1; i <= x; i++) {
for (var k = 1; k <= x - i; k++) {
document.write(" ");
}
for (var j = 1; j <= i; j++) {
document.write("*");
}
document.write("<br/>");
}
for (var i = x - 1; i >= 1; i--) {
for (var k = 1; k <= x - i; k++) {
document.write(" ");
}
for (var j = 1; j <= i; j++) {
document.write("*");
}
document.write("<br/>");
}
}
<body>
<input type="number" id="num" placeholder="Enter Number">
<br>
<button onclick="clicked()">SUBMIT</button>
</body>
添加回答
舉報(bào)