1

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
eyyMinda
  • 25
  • 5
  • 1
    Initialize a variable to `false`, then set it to `true` inside the loop. After the loop, do `if (variable) left--;`. You can also call `break;` to exit the loop. –  May 09 '22 at 20:43

3 Answers3

1

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--;
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

You can use this method:

 key = e.key.toLowerCase() 
Let decrement=false;
for (i = 0; i < word.length; i++) { 

if(decrement==false)
if (word[i] == key) { if (guessed[i] != key) { console.log(e.key) guessed[i] = key } else { left--;
decrement=true;} } }

Or you can just break out from the loop using break

0

Due to more conditions I decided so. Thank you for your answers! As a standard, got myself a few additional problems. Like first if{}else{} in the loop is executing both if and else instead of one or the other... So confusing.

    let correct = 0;
    let key = e.key.toLowerCase()
    for (i = 0; i < word.length; i++) {
        if (word[i] == key) {
            if (guessed[i] != key) {
                guessed[i] = key
                correct = 1;
                console.log(e.key)
            } else {
                console.log('Guessing same key')
                correct = 1;
            }
        }
    }
    if (correct != 1) {
        left--;
        console.log('Decrementing')
        tries.innerHTML += `<span>${key} </span>`
        correct = 0
    }
eyyMinda
  • 25
  • 5