地球上有人知道为什么这个 while 循环不能按预期工作吗?
我希望它创建一个 HTML 表格,但它生成了一行奇怪的单元格。
看一下......
var t = "<table>", i = 10 ; //h = 10;
while(i--> 0) {
//here was the problem declare the h var here
var h =10;
t += "<tr>";
while (h-->0) {
t += "<td> "+ h + "</td>";
}
t += "</tr>";
}
t += "</table>";
$("body").append($(t));
html,body {
margin-top:20px;
height:100%;
}
td {
border:1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>
JS Bin
</title>
</head>
<body>
</body>
</html>
最佳答案
您没有将 h
重置为 10
。一旦 i=9
进入 0
(i
的第一次迭代),它就会保持在 0
。
在外部循环开始时重置它:
var t="<table>",i=10;
while(i-->0){
var h = 10;
t+="<tr>";
while(h-->0){t+="<td>"+h+"</td>";}
t+="</tr>";
}
t+="</table>";
$("body").append(t); // no need for $(t) here
此处使用 for
语句可能有助于将初始化保持在循环附近,并且不会使程序变得不那么简洁(这看起来像您试图实现的目标):
var t="<table>";
for(var i=10;i--;){
t+="<tr>";
for(var h=10;h--;) t+="<td>"+h+"</td>";
t+="</tr>";
}
t+="</table>";
$("body").append(t);
当您忘记 var
声明(这是 JS 程序中的常见错误之一)时,这也会变得很明显。
关于javascript while() 循环创建一行单元格而不是表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091021/