1

I'm trying to make hangman for a Grade 12 Assessment piece.

I need to create variables due to the length of the current word chosen to be guessed. For example, if the word is 'cat', then

letter0 = 'c'
letter1 = 'a'
letter2 = 't'

So far, I have gotten some progress with a for loop.

for (i = 0; i <= currentWord.length){
  //var letter(i) = currentWord.charAt(i)
  i++
}

The commented out line was what I was aiming for, where the letter position would be put into the variable. Obviously this doesn't work, as the variable is just straight up read as letter(i) instead of letter(possible number). The loop would then stop once the length had been reached, and therefore there would be a unique variable for each letter of currentWord.

Any ideas of how to make this work?

Thanks!

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Mish_00
  • 33
  • 5
  • 3
    an [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) should be what you're looking for. – Hacketo Feb 23 '16 at 08:52
  • so how would I implement this with a loop? – Mish_00 Feb 23 '16 at 08:53
  • you can use the string method [`split()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) or the array method [push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Hacketo Feb 23 '16 at 08:54
  • 1
    use var letter = "cat".split(). then use letter[0], letter[1]..so on to get the letter. also for loop should be two semicolon(;) in it for good practice. so pass one at last – kp singh Feb 23 '16 at 08:57
  • 2
    I don't understand why this is getting downvoted. The question is perfectly clear, an attempt was made and posted, and the expected input and output are clear. Please don't downvote beginners' questions just because they're "easy" for you. – Madara's Ghost Feb 23 '16 at 08:58

3 Answers3

3

if you want to convert string to character array use currentWord.split("") it return array containing each character as element.

Pavan Teja
  • 3,192
  • 1
  • 15
  • 22
2

If looping is your goal, you don't even need to split, this works as expected:

const word = "cat";
for (let i = 0; i < word.length; i++) {
  console.log(word[i]); // Will output "c" then "a" then "t"
}

In most programming languages, strings are just arrays of letters anyway.

If you really want an array (there are things you can do to arrays and not to strings), you can use word.split("") which returns an array of letters.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

I'd suggest to split your word into an array, like Hacketo suggested:

var letters_array = "cat".split('');

Then you can loop over that array (check out the answers for Loop through an array in JavaScript)

Community
  • 1
  • 1
Simon Deconde
  • 309
  • 1
  • 4