-1

[

  // Define the variables
  var stringIn = [];
  var finalMessage = "Thanks for participating!";
  
  // Get input from user
  stringIn[0] = prompt("Enter the first string:");
  stringIn[1] = prompt("Enter the second string:");
  stringIn[2] = prompt("Enter the third string:");
  stringIn[3] = prompt("Enter the fourth string:");
  stringIn[4] = prompt("Enter the fifth string:");
  
  // For loop and display
  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn + "\n");
  }
  
  document.write("\n" + finalMessage);

My output should be: You entered: Alpha You entered: Bravo You entered: Charlie You entered: Delta You entered: Echo

but I'm getting:

You entered: Alpha,Bravo,Charlie,Delta,Echo You entered: Alpha,Bravo,Charlie,Delta,Echo You entered: Alpha,Bravo,Charlie,Delta,Echo You entered: Alpha,Bravo,Charlie,Delta,Echo You entered: Alpha,Bravo,Charlie,Delta,Echo

I've added my code to help with my problem. FireFox Web Console shows no errors and if I had an error, I wouldn't have any output. What is wrong with this code?

1
  • 1
    If you just write + stringIn +, how's it supposed to know which element of stringIn to use? Hence, write stringIn[myCounter] to access the element at index myCounter Commented Dec 3, 2019 at 20:53

3 Answers 3

2

You just need to access the index of the stringIn in your iterator.

stringIn[myCounter]

  // Define the variables
  var stringIn = [];
  var finalMessage = "Thanks for participating!";
  
  // Get input from user
  stringIn[0] = prompt("Enter the first string:");
  stringIn[1] = prompt("Enter the second string:");
  stringIn[2] = prompt("Enter the third string:");
  stringIn[3] = prompt("Enter the fourth string:");
  stringIn[4] = prompt("Enter the fifth string:");
  
  // For loop and display
  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn[myCounter] + "\n");
  }
  
  document.write("\n" + finalMessage);

Sign up to request clarification or add additional context in comments.

Comments

1

Should be

  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn[myCounter] + "\n");
  }

Comments

0

Less duplicates & array extras forEach

const stringsNumber = ['first', 'second', 'third', 'fourth', 'fifth'];
let greetingText = 'Hello, and Welcome to my survey!\n\n';

stringsNumber.forEach(string => {
  const promptValue = prompt(`Enter the ${string} string:`);
  greetingText += `You entered: \"${promptValue}\" to be the ${string} string.\n`;
})

greetingText += '\nThanks for participating!';

document.write(greetingText);
body {
  margin: 0;
  white-space: pre-line;
}

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.