sea.em.23
sea.em.23

Reputation: 3

JavaScript Word Generator

I'm making a word generator. You enter in ten strings of your choice. It should output one string that it randomly selected. It outputs a randomly selected number instead and it shouldn't. It should output a string entered by the user. I don't get errors.

How do I get this to display the user input?

Any suggestions? I've been stuck on this the last few days.

function randomWordGenerator() {

  // Define the variables
  var userInput = [];
  var answer = [], range = 1;
  var array = [];
  var set = [];

  // Prompt for String
  for(var index = 0; index < 10; index++) {
    userInput = prompt("Please enter string." + (index + 1));
    document.write("You entered: " + userInput + "\n");
  }

  // Generator
  for(var i = 0; i < range; i++) {
    answer[i] = Math.floor((Math.random() * 10) + 1);
  }

  // Generator Pick Display
  document.write("The generator choose: " + answer);
}

randomWordGenerator();

Upvotes: 0

Views: 101

Answers (1)

JLai
JLai

Reputation: 370

You have to save the user input into the array. What you are doing in your code is overwriting userInput all the time, i.e. only the last word the user entered is save in that variable. And then you generate some random numbers, push them all into an array and output that to the user. Here is how it would work:

function randomWordGenerator() {

  // Define the variables
  var array = [];

  // Prompt for String
  for (var index = 0; index < 10; index++) {
    var userInput = prompt("Please enter string." + (index + 1));
    array.push(userInput);
    document.write("You entered: " + userInput + "\n");
  }

  // select random number from array in which you stored the words
  var answer = array[Math.floor(Math.random() * array.length)];

  // Generator Pick Display
  document.write("The generator choose: " + answer);
}

randomWordGenerator();

Upvotes: 2

Related Questions