1 回答
TA贡献1963条经验 获得超6个赞
我对您的代码进行了细微修改。你几乎拥有它。我会按原样重用相同的嵌套 for 循环。只需更改循环的顶层。
金字塔的顶端运行:
for(var i=1; i<=x;i++)
底部金字塔用于:
for(var i=x-1; i>=1; i--)
您应该考虑将重复的嵌套代码移动到一个函数中,并将 的值i作为参数传递给该函数。
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>
添加回答
举报