I had problems with JavaScript and the "break" statements coming from the Ruby background.
Here is my function:
function isItTheNumber(numberToGuess){ if(previousGuess === null){ previousGuess = [playersGuess]; } previousGuess.forEach(function(guess){ if(playersGuess === guess && previousGuess > 1){ textStatus.style.display = 'block'; textStatus.innerHTML = 'You already picked that number'; } else if(parseInt(playersGuess) === parseInt(numberToGuess)){ textStatus.style.display ='block'; textStatus.innerHTML = 'You Are CORRECT!'; } else { previousGuess.push(playersGuess); textStatus.style.display='block'; textStatus.innerHTML = 'You are ' + hotOrCold(); document.getElementById('guess-count').innerHTML = playerGuessCount++; } }); }
In my .forEach loop, I would like to have a break statement for my first if statement. I would like the loop to stop if it ever executed this block.
I understand that I cannot use the break statement in this forEach function after reading a few posts about this. I tried to make a suggestion here using "everyone", but when I used this wrapped in a function, I could not return a true or false value.
I would like to avoid using any type of βbreakβ or hack for a break, but would use it if that is the only way. If anyone has suggestions on how I can rework my logic or suggest any suggestions, I would appreciate it. I have listed my logic in pseudo code below.
1) Check if the previousGuess array is null or populated. If it is null, set it to an array with the first value. 2) Iterate over the previousGuess array. 3) If: see if the user input (playerGuess) is in the previousGuess array. The previous guess array must be larger than 1. 4) Else If: If the users guess is the same as the a the value, tell them they are correct. 5) Else: if the users guess isn't the same as the value, tell them and add 1 to the playerGuessCount.
The problem with my current logic is that playerGuessCount is called too many times. If the array is iterated over and finds and the first if statement is true, it will still iterate the rest of the array, adding 1 to playerGuessCount, even if they only send 1 guess..forEach is strictly there to check if their assumption is a repeat.
Here is my attempt with "every" http://repl.it/P74
source share