-2

wondering how to make a simple function that would loop through a randomly chosen word and hold all of the letters (most likely in an array) for using in a hangman game. The code below just captures the last letter.

document.onkeyup = function(event) {                              
  var userInput = event.key;
  for(var i = 0; i < word.charAt[i]; i++)                               
    return i;  

1 Answers1

0

JS already has this functionality built in, see split. Split has a few shortcomings that are best explained here, but I think that for the problem you stated above is not important. To illustrate how it works see:

function getLetters(word) {
    return word.split('');
}

console.log(getLetters('hello'));

This will print out:

(5) ["h", "e", "l", "l", "o"]

Also please note that you can access each character with its index using normal array syntax:

let s = "some";

console.log(s[3]); // logs 'e'

You can also use the spread operator, available since ES2015 (ES6)

let arr = [...word];

OR

let arr = Array.from(word);
lloiacono
  • 4,714
  • 2
  • 30
  • 46
  • 1
    Don't know why, but I fixed it (I still think the question is unclear though) – Alon Eitan Oct 18 '18 at 17:27
  • Not my down vote, but with the code that is shown in the question it is not clear to me at all that this is what OP is asking. And even if this is it, it should have been closed as a duplicate of [How do you get a string to a character array in JavaScript?](https://stackoverflow.com/questions/4547609/how-do-you-get-a-string-to-a-character-array-in-javascript). The prime goal of SO is to create a repository of high quality questions and answers. Being a new comer is not an excuse to ask low quality questions. If a question is low-quality, is should be down voted. It's what votes are for. – Ivar Oct 18 '18 at 17:29