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
1
  • 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. Commented May 9, 2022 at 20:43

3 Answers 3

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--;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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
    }

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.