admin管理员组文章数量:1426066
I have this for loop, and it seems to be repeating the first loop twice (x=0) and then not doing the last one (x=2)
for (x=0;x<=2;x++)
{
if (document.getElementById("sub"+catCount+x).value != "")
{
if (nonums.test(document.getElementById("sub"+catCount+x).value))
{
total = total + parseFloat(document.getElementById("sub"+catCount+x).value);
}
}
alert(x);
}
In other words, I get two alert boxes with "0" in them, then one with "1" in it, and that's it.
Can anyone tell me what I'm not seeing here? Why doesn't it just progress through the loop normally (0,1,2)?
I have this for loop, and it seems to be repeating the first loop twice (x=0) and then not doing the last one (x=2)
for (x=0;x<=2;x++)
{
if (document.getElementById("sub"+catCount+x).value != "")
{
if (nonums.test(document.getElementById("sub"+catCount+x).value))
{
total = total + parseFloat(document.getElementById("sub"+catCount+x).value);
}
}
alert(x);
}
In other words, I get two alert boxes with "0" in them, then one with "1" in it, and that's it.
Can anyone tell me what I'm not seeing here? Why doesn't it just progress through the loop normally (0,1,2)?
Share Improve this question asked Jun 25, 2010 at 21:48 JimmyJimmy 2,9256 gold badges45 silver badges57 bronze badges 6- 3 Given that x is (possibly) declared as a global, does anything else in the functions you have called alter it? – Yacoby Commented Jun 25, 2010 at 21:50
- 2 This part of the code is not causing the problem. Can you point us to a URL of the whole site? – phihag Commented Jun 25, 2010 at 21:52
- that is literally the only spot I use the variable x on any page. – Jimmy Commented Jun 25, 2010 at 21:53
- @phihag: I can't, really. I'd need to give you a login. – Jimmy Commented Jun 25, 2010 at 21:55
- what happens if you change the variable name? – Dr. belisarius Commented Jun 25, 2010 at 22:03
2 Answers
Reset to default 2that is literally the only spot I use the variable x on any page.
It works for me.
for (x=0;x<=2;x++)
{
alert(x);
}
You can test it at console.
I don't think you want the variable x to be global in scope. Try it with the "var" keyword:
for (var x=0;x<=2;x++)
...
I can paste this in my address bar and it will produce 0, 1, 2.
javascript:for (var x=0;x<=2;x++) {alert(x);}
I tried it in IE, FF and Chrome.
本文标签: javascriptFor Loop repeats first loop twiceStack Overflow
版权声明:本文标题:javascript - For Loop repeats first loop twice - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745444628a2658606.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论