Javascript for 循环中的多个计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8348792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple counters in Javascript for loop
提问by benhowdle89
Before i tear my hair out and go down the wrong path in terms of debugging. Can someone confirm that this code will do as intended. Ie. animate 5 divs to different positions:
在我撕掉头发并在调试方面走错路之前。有人可以确认此代码会按预期执行。IE。将 5 个 div 动画到不同的位置:
var i, j, k;
$('#menuButton').click(function(){
for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){
$('.spinner #item' + i).animate({
left: '+=' + j,
bottom: '+=' + k
}, 500, function() {
// Animation complete.
});
}
});
When i click the #menuButton
, nothing happens and I get this error:
当我单击 时#menuButton
,没有任何反应,我收到此错误:
Uncaught SyntaxError: Unexpected token ; on the 'for()' line...
未捕获的语法错误:意外标记;在“for()”行...
回答by J. Holmes
You've got some semicolons where you want commas:
你有一些需要逗号的分号:
for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30) { /* do work */ }
You should only have three "statements" inside your for
你应该只有三个“声明”在你的 for
for( [init]; [test]; [increments]) { [block] }
To do multiple [inits]
or [increments]
you have to use the sometimes magical, but oft forgotten, comma operator
做多个[inits]
或者[increments]
你必须使用有时神奇但经常被遗忘的逗号运算符
回答by jAndy
too much semicolons there
分号太多了
for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){
should be
应该
for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30){
回答by Incognito
You made gramatical errors in your code that you could have easily spotted had you used static code analysis tools such as the lovely JSHint.
如果您使用静态代码分析工具(例如可爱的JSHint ),您很容易发现代码中存在的语法错误。
In addition, you should further understand the use of the comma operatorin JavaScript, our site has a few answers on it already.