sideroxylon
sideroxylon

Reputation: 4416

Conditional statement inside for loop

II have a basic for loop to loop through a data feed:

for(var i = 0; i<items.length; i++) {

Then several variables are defined in this form:

var x = items.content[i]

Now I want to do something if one of the values of x equals a value from outside the loop (y):

if (x == y) { //do something }

All values of x and y will always be unique, so there can never be more than one match - but there may be none.

The problem comes next - I want to do something else if there is no match, if no value of x matches y.

If I just do something like:

else { //do something else }

the else condition is also satisfied by other values of x. I have tried putting break; after the if condition, but unless the match is found on the first value of x, both conditions are satisfied and both actions are triggered. How do I construct this so that the first action is triggered if there is a match between x and y, but the second action is triggered only if all values of x don't match y?

Thanks for any suggestions or advice.

Upvotes: 1

Views: 9109

Answers (1)

manji
manji

Reputation: 47968

Create a boolean that will hold the result of finding 'y', then execute the actions outside of the loop depending on that boolean:

var match = false;

for(var i = 0; i<items.length; i++) {
    var x = items.content[i]
    if(x == y) {
        match = true;
        // a match is found, there is no need to continue, 
        break;
    }
}

if(match) {
    //do something
} else {
    //do something else
}

Upvotes: 4

Related Questions