2

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?

1
  • 1
    if you start i at 0, you should use i < itemsAll not <=. For example if there are 10 items and you start at i=0 you'd want to stop at i=9 Commented Jul 19, 2010 at 5:20

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the reverse loop, because the 'removeItem' may cause the remaining items to be renumbered. Although the loop should probably start from itemAll-1 and continue when i>=0.
0

You can use an if test in your for loop as already suggested, or you can split your for loop in two.

x = Math.min(current, itemsAll);
for(i=0;i<x;++i){
   removeItems(i);
}
for(i=x+1; i<itemsAll;++i)
{
   removeItems(i);
}

Comments

0

We can solve the problem using continue statement too.Detail about continue can be found here and a very simple use of continue can be seen here

var current = 2;
for(var i = 0; i<=itemsAll; i++) {
    if( i === current) { continue; }
    removeItem(i);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.