Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for Loop with if-else statement

I would like to ask some logic question here.

Let say I have a for loop in javascript to remove the whole items:-

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.

how do I or where do I add a if-else statement in this current for loop?

Please help, anyone?

like image 687
JamesQuay Avatar asked Jan 26 '26 11:01

JamesQuay


1 Answers

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.

like image 50
S73417H Avatar answered Jan 27 '26 23:01

S73417H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!