js中for双循环金字塔
时间: 2023-12-24 16:56:50 浏览: 78
金字塔的打印的实现for循环
在JavaScript中,使用双重循环可以打印出金字塔形状。首先,需要接收用户输入的金字塔行数。然后,使用两个嵌套的for循环来打印金字塔的每一行。外层循环控制行数,内层循环控制打印空格和星号的数量。以下是一个示例代码:
```javascript
var ta = prompt("请输入金字塔的行数");
for (var i = 1; i <= ta; i++) {
for (var j = 1; j <= ta - i; j++) {
document.write(" ");
}
for (var k = 1; k <= 2 * i - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
```
这段代码可以根据用户输入的行数,打印出对应行数的金字塔形状。外层循环控制行数,内层循环第一个循环打印空格,个数为行数减去当前行数;内层循环第二个循环打印星号,个数为当前行数的两倍减一。通过循环嵌套,我们可以打印出一个带有空格的金字塔形状。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [jsfor循环打印金字塔](https://blog.csdn.net/qq_45637785/article/details/102770071)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [JavaScript使用for循环打印金字塔](https://blog.csdn.net/a_rain2333/article/details/106538275)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文