arrays - How do I dynamically insert and access objects within objects in Javascript? -
let's have object
var employee = [];
how prompt (with prompt function) user input info looks this:
var employee = [ {"firstname":"john", "lastname":"doe"}, {"firstname":"anna", "lastname":"smith"}, {"firstname":"peter", "lastname": "jones"} ];
of course of study unspecified number of arrays. if user inputs info 1 employee , inputs nil or hits cancel array have 1 array (for john doe).
the main thing though user inputs info until decide done. unspecified number of arrays.
i need looping prompt though understand prompts suck. lot.
so here's i'm trying do:
prompt user employee. illustration input: john doe take string, utilize split function. after have array named john doe loop above until user inputs "" or clicks cancel. store employees object can printed console.this code looks like.
var person = {firstname: "", lastname: ""} var employee = []; //used store each person var input = "x"; for(var = 0; input != "" && input != null; i++){ var input = prompt("input first , lastly name"); var results = input.split(); //create array input person.firstname = results[0]; person.lastname = results[1]; employee[i] = person;//store person array client array. } console.log(employee[1]["firstname"]); //test output console.log(employee[0]["lastname"]); //test output
when test output undefined. trying access specific person's first name unable to.
you can this
var flag = true, arr = []; while (flag) { arr.push({ firstname: prompt("what's first name?") || "john", lastname: prompt("what's lastly name?") || "doe" }); flag = confirm("do want continue?"); }
or else, can do
var arr = (prompt("what's name first , lastly name") || "john doe").split(" "); arr.push({ firstname: arr[0], lastname: arr[1] });
javascript arrays
No comments:
Post a Comment