for循环嵌套
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span {
display: inline-block;
margin: 10px;
}
</style>
</head>
<body>
<script>
for (let i = 1; i < 10; i++) {
for (let j = 1; j <= i; j++) {
document.write(`<span>${j}*${i}=${i * j}</span>`);
}
document.write(`<br/>`)
}
</script>
</body>
</html>
运行结果:
while循环嵌套
代码:
<!DOCTYPE html>
<html>
<head>
<title>九九乘法表</title>
</head>
<body>
<table>
<tbody id="multiplication-table"></tbody>
</table>
<script>
var table = document.getElementById("multiplication-table");
var i = 1;
while (i <= 9) {
var row = document.createElement("tr");
var j = 1;
while (j <= i) {
var cell = document.createElement("td");
cell.textContent = i + " x " + j + " = " + (i * j);
row.appendChild(cell);
j++;
}
table.appendChild(row);
i++;
}
</script>
</body>
</html>
运行结果: