Search code examples
javascriptarraysif-statementfor-loopprompt

How to put user input into an array? Can for statements go inside an if/else statement? (Javascript)


I understand this may contain completely inane methods, but I am just playing around here to learn. My question is whether or not one can use an if statement inside an if/else statement like I have done. Lastly, how would you go about prompting for input and putting it into an array?

var inputArr1 = prompt('Type a noun');
var inputArr2 = prompt('Type another noun');
var inputArr3 = prompt('Type another noun');
var inputArr4 = prompt('Type a final noun');

document.getElementById("inputArr1").value;
document.getElementById("inputArr2").value;
document.getElementById("inputArr3").value;
document.getElementById("inputArr4").value;

var recordedArray = [ inputArr1, inputArr2, inputArr3, inputArr4 ];

if (recordedArray.length == 3){
    for (var i = 0; i <= recordedArray.length; i++){
         console.log("I like to eat " + recordedArray[i] + " with ketchup!");
}
else {
    console.log("You did not type a proper entry or something. Try again.");
     }
}

Solution

  • Prompting user and saving responses to an array can be done like this:

    var questions = [ "question1", "question2", "question3" ];
    var answers = [];
    for (var i = 0; i < questions.length; i++) {
      answers.push(prompt(questions[i]));
    }
    console.log(answers);
    

    It looks like you have something wrong with braces around if-else statement (everything is in if and else refers to for loop), but the idea was good. Moreover you need to know that your recordedArray length will be equal to 4, not 3.

    Furthermore the code below does nothing or generates errors:

    document.getElementById("inputArr1").value;
    document.getElementById("inputArr2").value;
    document.getElementById("inputArr3").value;
    document.getElementById("inputArr4").value;
    

    document.getElementById() looks for HTML element, if it does not exist you will get

    TypeError: Cannot read property 'value' of null
    

    so i recommend to remove these lines of code.