I have hit a block in working on an assignment. How do I insert a value to a given index or indices?
For example, I'm working on a hangman game. If the word is "harry", and the player guesses the letter "r" how do I turn my array of underscores to "_ _ r r _"?
what I have below gets a word from a separate js file, creates an array of underscores (one for each letter of the returned word), and then, when a user guesses a letter, it finds the index or indices of the occurrences of that letter.
**I've updated the code below. The for loop towards the end goes my array of underscores (wordToGuess[]) and splices in the users input. This does what I need it but it also puts the last guessed letter in the front. For example if the word was "bold" and the last letter the user guessed was "l", the wordToGuess array would be lbold. Does anyone here know why this is? I'm sure its something easy I'm overlooking, but its driving me nuts.
Javascript
var word;
$(document).ready(function () {
SetGameBoard();
});
//When guess button is clicked
$('#BtnGuess').click(function () {
CheckGuess();
});
function GetPhrase() {
word = ReturnWord();
alert(word);
}
function SetGameBoard() {
GetPhrase();
wordToGuess = new Array(word.length);
// Place underscore for each letter in the answer word in the DivWord div
for (var i = 0; i < word.length; i++){
wordToGuess[i] = "_ ";
}
$('#DivWord').html(wordToGuess);
}
function CheckGuess() {
var pos = 0;
var posArray = [];
var guessLetter = $('#tbGuessLetter').val();
while ((pos = word.indexOf(guessLetter, pos)) > -1) {
posArray.push(++pos);
}
if (posArray.length == 0) {
alert(guessLetter + " is not in the word.");
}
//Splice in correct letters. Not working 100%
for(i=0; i < wordToGuess.length; i++){
wordToGuess.splice(posArray[i], 1, guessLetter);
}
$('#DivWord').html(wordToGuess);
alert(posArray);
alert(guessLetter);
}