Search code examples
javascriptloopsvariablesincrementdecrement

How to increment/decrement variable value only once while in a loop?


I need to decrement var "left" by 1 and only once instead of having it go through a loop and decrement if conditions pass true. But conditions are valid only if they are in a loop. How would I do this?

 let key = e.key.toLowerCase()
    for (i = 0; i < word.length; i++) {
        if (word[i] == key) {
            if (guessed[i] != key) {
                console.log(e.key)
                guessed[i] = key
            } else {
                console.log('This is where i want left--')
            }
        }
    }
    left--;  //Need this to decrement only once

Solution

  • Store whether left has been decremented in a variable:

    let key = e.key.toLowerCase()
    let decrementedLeft = false;
    for (i = 0; i < word.length; i++) {
        if (word[i] == key) {
            if (guessed[i] != key) {
                console.log(e.key)
                guessed[i] = key
            } else {
                if(!decrementedLeft){
                    decrementedLeft = true;
                    left--;
                }
            }
        }
    }
    if(!decrementedLeft){
        left--;
    }