Let's say you have an object
var employee = [];
How would you prompt (with the prompt function) the user to input information so that it looks like this:
var employee = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}
];
Of course with an unspecified number of arrays. So if your user only inputs information for one employee and then inputs nothing or hits cancel the array will only have one array (for John Doe).
The main thing though is that the user inputs information until they decide that they are done. So an unspecified number of arrays.
I need to do this with a looping prompt even though I understand that prompts suck. A lot.
So here's what I'm trying to do:
- Prompt user for an employee. Example input: John Doe
- Take string, use split function. After which you would have an array named John Doe
- Loop the above until user inputs "" or clicks cancel.
- Store all the employees into an object that can be printed to the console.
This is what my code looks like.
var person = {firstname: "", lastname: ""}
var employee = []; //used to store each person
var input = "x";
for(var i = 0; input != "" && input != null; i++){
var input = prompt("Input first and last name");
var results = input.split(); //create an array from the input
person.firstname = results[0];
person.lastname = results[1];
employee[i] = person;//store the person array into the customer array.
}
console.log(employee[1]["firstname"]); //test output
console.log(employee[0]["lastname"]); //test output
when I test my output however I get undefined. I am trying to access a specific person's first name but an unable to.