I’m creating a Hangman game using jQuery. I seem to be having trouble with repeating letters while using indexOf
. When I pick a correct letter it only fills in the first slot and won’t fill in the second, even if you click the same letter twice.
Example:
Name: “bob”
Typed character: “b”
Outcome: “b__”
Expected outcome: “b_b”
I tried to convert this over to using a loop, but it become an endless loop.
// Band Names array
var bandNames = ["AJJ", "Bob Dylan", "The Front Bottoms", "The Hotelier"];
var correctLetters = [];
var placeHolder = [];
// creates a random number between 1 and the length of the band array.
var randomNumber = Math.floor(Math.random() * bandNames.length);
// picks a random band based of the length of the randomband array
var selectedBand = bandNames[randomNumber];
// add place holder based on length of band name
for (i = 0; i < selectedBand.length; i++) {
placeHolder.push("<li></li>");
}
$(document).keypress(function(e) {
var letterClicked = String.fromCharCode(e.which);
if (selectedBand.indexOf(letterClicked) > -1) {
// adds correct letter to the array
correctLetters.push(letterClicked);
placeHolder[selectedBand.indexOf(letterClicked)] = letterClicked;
// combines the array
var joinArray = placeHolder.join("");
// appand
$('#current-container').html("").append(joinArray);
if (joinArray == selectedBand) {
alert("you win");
location.reload();
}
}
});
How can I find all the characters?