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
CodePudding user response:
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
CodePudding user response:
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
}
CodePudding user response:
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--;
}