-4

I am currently making a simple hang-man game using a browser.

When the user clicks on a button, it calls a function pickWord():

    <button onclick="pickWord()" id="restart">Pick A Word</button>

The function then picks a random word from the dictionary, assigns it to a variable, and creates the spaces ( _ _ _ _) for the word to put in an html table.

    function pickWord()
    {
        var word = dictionary[Math.floor(Math.random()*dictionary.length)];
        wordSpaces = "_" * word.length;
        document.getElementById('spaces').innerHTML = wordSpaces;

    }

This is not working: The spaces are not displayed on the table.

I made a JSFiddle to help solve the problem.

JoshK
  • 425
  • 1
  • 4
  • 18
  • 1
    At least in your fiddle, you're missing a comma after "Hangman" in your array. You're also going to have an issue because `"_" * word.length;` won't work. – krillgar Apr 23 '15 at 00:19
  • Ok thanks! Is there a way to make the number of spaces = the length of the word? – JoshK Apr 23 '15 at 00:21
  • 1
    Check out [this question](http://stackoverflow.com/questions/1877475/repeat-character-n-times) for that solution. `Array(word.length).join('_');` – krillgar Apr 23 '15 at 00:23

3 Answers3

1

You can't apply multiplication to a string and a number, so you need to use a loop to build the wordSpaces string.

There is a comma missing after the first line in the dictionary array.

In your JSFiddle, the javascript code was wrapped inside the onLoad function, so you didn't have a pickWord in the global scope.

updated: https://jsfiddle.net/24eqxLpn/1/

user
  • 6,567
  • 18
  • 58
  • 85
0
function pickWord() {
    var word = dictionary[Math.floor(Math.random()*dictionary.length)];

    var wordSpaces = '';
    for(var i=0;i<word.length;i++) {
        wordSpaces += '_'; // append
    }

    document.getElementById('spaces').innerHTML = wordSpaces;

}
Ruslanas Balčiūnas
  • 7,310
  • 3
  • 24
  • 41
0

Your first pb comes from your table, you missed a comma , Javascript crashes after that.

aorfevre
  • 5,034
  • 3
  • 21
  • 51