Home > front end >  add Array using for loop (JS)
add Array using for loop (JS)

Time:05-06

I'm recreating a hangman game where I create a random word and conceal this with "". i.e if the word is "monkey" then the array should be ["", "", "", "", "", "_"].

With the following code, the alert ends up displaying ",,,,," or "". I've tried searching for the answer, tried .push method and rearranged the code to no avai.

also, this code is example code out of a beginners book so I'm not sure if it's simply just outdated now.

Appreciate if anyone can shed some light on how I could get this to work with basic beginner syntax.

// Attempt 1:

var words = [
    "javascript",
    "monkey",
    "amazing",
    "pancake"
];

var word = words[Math.floor(Math.random() * words.length)];
console.log(word);

var answerArray = [];
for (var i = 0; i < word.length; i  ); {
    answerArray[i] = "_";
}

alert(answerArray);
// outputs ",,,,,,_"

///Attempt 2:
//Same code as above but with:

alert(answerArray.join(" "));
// outputs single "_"

///Attempt 3
//as above but with:

var answerArray = [];
for (var i = 0; i < word.length; i  ); {
    answerArray.push("_");
}

alert(answerArray.join(" "));
// outputs single "_"

CodePudding user response:

First Quick tipp use let instead of var. Then in your first attempt in the initialization of the for loop, you have a semicolon after the closing bracket. This terminates the statement and the for-body (between the {}) gets not executed. so remove that semicolon and you're good to go

CodePudding user response:

      const words = [
          "javascript",
          "monkey",
          "amazing",
          "pancake"
       ];

      var word = words[Math.floor(Math.random() * words.length)];
      console.log(word);

      var answerArray = [];
      for (var i = 0; i < word.length; i  ) {
              answerArray[i] = ",";
      }

      console.log(answerArray[0])

      alert(answerArray);

Remove the semicolon in for loop and you are ready to go.

      [ ',', ',', ',', ',', ',', ',', ',', ',', ',', ',' ]

CodePudding user response:

Remove semicolon after the for loop declaration and before the body of for loop. This semicolon is making your for loop to end as soon as it get declared.

var words = [
"javascript",
"monkey",
"amazing",
"pancake"
];

var word = words[Math.floor(Math.random() * words.length)];
console.log(word);

var answerArray = [];
for (var i = 0; i < word.length; i  ) {
answerArray[i] = "_";
}

alert(answerArray);
  • Related