Home > front end >  JavaScript for loop issue affects guess count
JavaScript for loop issue affects guess count

Time:04-10

so I'm trying to build a JavaScript hangman game and I'm having a problem with my checkMatch function. what I'm trying to achieve is for it to check against the hiddenChoice array and only run the code in the else if statement if this.id isn't in the array at all. currently if hiddenChoice = apple and this.id = l it will return 'guess again' 3 times before it returns that 'you found a letter' when it hits l, which affects my guess count. All of the console.logs are in there so I could figure out what was going on. thanks for the help.

function checkMatch(){
    console.log(hiddenChoice)
 for (let k = 0; k < hiddenChoice.length; k  ){
        if (this.id === hiddenChoice[k]){
            console.log('you found a letter')
            console.log(this.id)
            greenColor = this.id
            green(greenColor)
            right  
            console.log(right)
            return
        }
        else if (this.id != hiddenChoice[k]) {
            console.log('guess again')
            console.log(guesses)
            console.log(this.id)
            redColor = this.id
            red(redColor)
            guesses--
        }
    }

CodePudding user response:

The else shouldn't be inside the loop, because you cannot yet know whether any of the next characters would match. Only when the loop has finished you know that none of the letters matched.

So:

function checkMatch(){
    console.log(hiddenChoice)
    for (let k = 0; k < hiddenChoice.length; k  ){
        if (this.id === hiddenChoice[k]){
            console.log('you found a letter')
            console.log(this.id)
            greenColor = this.id
            green(greenColor)
            right  
            console.log(right)
            return
        }
    }
    console.log('guess again')
    console.log(guesses)
    console.log(this.id)
    redColor = this.id
    red(redColor)
    guesses--
}

Some other remarks:

  • Your code uses several variables which are not declared, or at least global. This should be avoided. Declare temporary variables (like greenColor?) as local variables (e.g. with let).

  • End your statements with a semi-colon. JavaScript does this automatically when you don't, using some rules, but you don't want that to happen as there are some pitfalls.

  • It is not clear what this is. It would be better if id were passed as argument to the function.

  • Your code will not work as expected if a single guess has multiple matches. Try to think how you could manage that (as an exercise).

  • Related