jquery - insert values at certain index (or indices) javascript -
i have hit block in working on assignment. how insert value given index or indices?
for example, i'm working on hangman game. if word "harry", , player guesses letter "r" how turn array of underscores "_ _ r r _"?
what have below gets word separate js file, creates array of underscores (one each letter of returned word), , then, when user guesses letter, finds index or indices of occurrences of letter.
**i've updated code below. loop towards end goes array of underscores (wordtoguess[]) , splices in users input. need puts last guessed letter in front. example if word "bold" , last letter user guessed "l", wordtoguess array lbold. here know why is? i'm sure easy i'm overlooking, driving me nuts.
javascript
var word; $(document).ready(function () { setgameboard(); }); //when guess button clicked $('#btnguess').click(function () { checkguess(); }); function getphrase() { word = returnword(); alert(word); } function setgameboard() { getphrase(); wordtoguess = new array(word.length); // place underscore each letter in answer word in divword div (var = 0; < 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 + " not in word."); } //splice in correct letters. not working 100% for(i=0; < wordtoguess.length; i++){ wordtoguess.splice(posarray[i], 1, guessletter); } $('#divword').html(wordtoguess); alert(posarray); alert(guessletter); }
for modifying arrays in place, want array.prototype.splice()
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/splice
from docs:
var myfish = ['angel', 'clown', 'mandarin', 'surgeon']; // removes 0 elements index 2, , inserts 'drum' var removed = myfish.splice(2, 0, 'drum'); // myfish ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removed [], no elements removed // removes 1 element index 3 removed = myfish.splice(3, 1); // myfish ['angel', 'clown', 'drum', 'surgeon'] // removed ['mandarin'] // removes 1 element index 2, , inserts 'trumpet' removed = myfish.splice(2, 1, 'trumpet'); // myfish ['angel', 'clown', 'trumpet', 'surgeon'] // removed ['drum'] // removes 2 elements index 0, , inserts 'parrot', 'anemone' , 'blue' removed = myfish.splice(0, 2, 'parrot', 'anemone', 'blue'); // myfish ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removed ['angel', 'clown'] // removes 2 elements index 3 removed = myfish.splice(3, number.max_value); // myfish ['parrot', 'anemone', 'blue'] // removed ['trumpet', 'surgeon']
it looks behavior want in third example here replace 'drum' 'trumpet'.
Comments
Post a Comment