0

I'm attempting to create a guessing game where everytime the user clicks a character it will be stored in a variable to form a string. Let's say for example... (c t p i j a r a v s) so if the user clicks J A V A S C R I P T respectively, It will be stored in a variable as "javascript" and will be recognized as the correct answer .and my code looks like this:

clickcount = 0;
$(".gameletter").click(function() {
keyletter = $(this).attr("ID");
vars['m' + clickcount] = keyletter;
clickcount++;

}
}); 

but I don't know how to combine every keyletter to form a string... Thank you

2 Answers 2

1

Use an array instead of an object to store the letters, and combine them into a string using join():

var clickcount = 0;
var letters = [];

$(".gameletter").click(function() {
    var letter = $(this).attr("ID");
    letters.push(letter);
    clickcount++;
});

// ...

var string = letters.join('');
Sign up to request clarification or add additional context in comments.

1 Comment

push() would be better
1

I would solve this problem by splitting the target word into an array and removing letters as they guess correctly. Once the word array length is 0, they have won:

var word = 'javascript'.split(''); // ['j', 'a', 'v', 'a' ...]

function guessLetter(guess) {
  if(word.indexOf(guess) > -1) {
    // remove correct letter guess from word
    word.splice(word.indexOf(guess), 1);
  }

  if(word.length === 0) {
    console.log('you win');
  }
}

guessLetter('j');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.