Javascript 带有 if-else 语句的 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3278556/
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
for Loop with if-else statement
提问by JamesQuay
I would like to ask some logic question here.
我想在这里问一些逻辑问题。
Let say I have a for loop in javascript to remove the whole items:-
假设我在 javascript 中有一个 for 循环来删除整个项目:-
var i = 0;
for (i=0;i<=itemsAll;i++) {
removeItem(i);
}
I do not want to remove item when i = current = e.g. 2 or 3.
当 i = current = 例如 2 或 3 时,我不想删除项目。
how do I or where do I add a if-else statement in this current for loop?
我如何或在此当前 for 循环中添加 if-else 语句?
Please help, anyone?
请帮忙,有人吗?
回答by S73417H
Iterate over it in reverse order and only remove the items which does not equal the current item.
以相反的顺序迭代它,只删除不等于当前项目的项目。
var current = 2;
var i = 0;
for (i=itemsAll-1;i>=0;i--) {
if (i != current) {
removeItem(i);
}
}
I probably should have stated the reason for the reverse loop. As Hans commented, the loop is done in reverse because the 'removeItem' may cause the remaining items to be renumbered.
我可能应该说明反向循环的原因。正如 Hans 评论的那样,循环是反向完成的,因为“removeItem”可能会导致剩余的项目重新编号。
回答by patros
You can use an if test in your for loop as already suggested, or you can split your for loop in two.
您可以按照已经建议的那样在 for 循环中使用 if 测试,也可以将 for 循环一分为二。
x = Math.min(current, itemsAll);
for(i=0;i<x;++i){
removeItems(i);
}
for(i=x+1; i<itemsAll;++i)
{
removeItems(i);
}
回答by Nitin Kumar
We can solve the problem using continuestatement too.Detail about continue can be found hereand a very simple use of continuecan be seen here
我们也可以使用continue语句来解决问题。关于 continue 的详细信息可以在这里找到,一个非常简单的continue用法可以在这里看到
var current = 2;
for(var i = 0; i<=itemsAll; i++) {
if( i === current) { continue; }
removeItem(i);
}

