[
// 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?
3 Answers 3
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);
Comments
Should be
for(var myCounter = 0; myCounter < 5; myCounter++) {
document.write("You entered: " + stringIn[myCounter] + "\n");
}
Comments
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;
}
+ stringIn +, how's it supposed to know which element ofstringInto use? Hence, writestringIn[myCounter]to access the element at indexmyCounter