我正在使用javascript制作计算器程序
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var buttonname = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "C", "Enter"];
</script>
</head>
<body>
<script type="text/javascript">
var n = 0;
for (var i = 0; i < buttonname.length; i++) {
document.write("<button>" + buttonname[i] + "</button>");
if (i = 3 * n, n++)
document.write("<button>" + buttonname[i] + "</button><br>");
}
</script>
</body>
</html>
&#13;
输出应该是这样的:
1 2 3 4
5 6 7 8
9 0 + -
但我的输出是
1 2 4
5 7
8 0
/输入
有什么问题?我看到3,6,9, - ,C按钮消失但为什么?当for循环传递3 * n索引时,我只想创建一个新行。 (表示按钮4,8之后的新行...)
答案 0 :(得分:0)
document.write
是一种向网页添加动态内容的可怕方式,但除此之外你的逻辑是错误的
我想在for循环传递3 * n索引
时创建一个新行
你真正想要的是在数组中每第4个元素之后的<br/>
for(var i = 0; i <buttonname.length; i++){
if(i != 0 && (i%4) == 0)
document.write("<br>");
document.write("<button>"+buttonname[i]+"</button>");
}
var buttonname = ["1","2","3","4","5","6","7","8","9","0","+","-","*","/","C","Enter"];
var n=0;
for(var i = 0; i <buttonname.length; i++){
if(i != 0 && (i%4) == 0)
document.write("<br>");
document.write("<button>"+buttonname[i]+"</button>");
}
答案 1 :(得分:0)
如何使用modulo
?
var buttonname = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "C", "Enter"];
for (var i = 0; i < buttonname.length; i++) {
document.write("<button>" + buttonname[i] + "</button>");
if (i % 4 == 3) {
document.write("<br>");
}
}
答案 2 :(得分:0)
我认为这就是你要找的东西:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var buttonname = ["1","2","3","4","5","6","7","8","9","0","+","-","*","/","C","Enter"];
</script>
</head>
<body>
<script type="text/javascript">
var n=0;
for(var i = 0; i <buttonname.length; i++){
document.write("<button>"+buttonname[i]+"</button>");
if(i!=0 && (i+1)%3==0)
document.write("<br>");
}
</script>
</body>
</html>
答案 3 :(得分:0)
检查你的if块,逻辑似乎被打破了。 将它替换为下面的if块,你就可以了。
if( (i+1) %3 == 0)
document.write("<br />");
检查运行索引是否是3的倍数,如果是,则插入换行符。 i + 1是必需的,因为你的循环以0开头。
你必须特别注意你的结构和方式。写下你的代码。很抱歉,你说你的代码手写不好&#39;。
输出SS enter image description here
这个JavaScript array tutorial非常好,而且代码格式也很好。