简体   繁体   中英

How can I optimize a for-loop over a list of specific conditions?

I've got a for-loop in JavaScript, iterating over the variable i. In each iteration step, a list of if-conditions is checked. For each i, only one of these conditions can be true (or none of them) and every condition is true for exactly one i. A very simple example would be:

for (i = 1; i <= 10; i++)
{
if (i === 3) {some code ...}
if (i === 7) {some other code ...}
 }

So obviously for 4 <= i <= 10 the condition i === 3 will always fail. Is there a way to achieve that if a condition is true for some i, this condition will not be checked any more for the other i's? Can this condition be deleted in some way? This would make the loop much faster.

(Of course the example of above does not make much sense and the real use case is much more complicated.)

Thank you in advance for your help!

Switch is better for what you're trying to achieve

for (i = 1; i <= 10; i++)
{
 switch(i){
  case 1:
   some code..;
   break; //once this is called, the statement will stop
  case 3:
   some other code..;
   break;
 }
}

You can use else if statements to skip all of the other conditions once one is found.

for (i = 1; i <= 10; i++) {
    if (i === 3) {some code ...}
    else if (i === 7) {some other code ...}
}

In this case, if i is 3, the other conditions will be skipped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM