如何在循环中仅 increment/decrement 变量值一次?

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

我需要将 var "left" 递减 1,并且只递减一次,而不是让它经历一个循环并在条件为真时递减。但是条件只有在循环中才有效。我该怎么做?

 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

存储left是否递减到一个变量中:

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--;
}

你可以使用这个方法:

 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;} } }

或者您可以使用 break

从循环中跳出

由于更多的条件,我决定这样做。谢谢您的回答! 作为标准,给自己带来了一些额外的问题。就像循环中的第一个 if{}else{} 同时执行 if 和 else 而不是一个或另一个...如此混乱。

    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
    }