假設你有一個對象如何在Javascript中動態插入和訪問對象中的對象?
var employee = [];
你將如何提示(與提示功能)用戶輸入信息,使得它看起來像這樣:
var employee = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}
];
當然有數目不詳的陣列。所以,如果你的用戶只輸入一個員工的信息,然後輸入什麼或命中取消數組將只有一個數組(對於John Doe)。
但主要的是用戶輸入信息,直到他們決定完成。所以沒有指定數量的數組。
我需要用循環提示來做到這一點,即使我明白提示吸吮。很多。
因此,這裏是我想要做的事:
- 爲僱員提示用戶。示例輸入:John Doe
- 取字符串,使用分割函數。之後,您將有一個名爲John Doe的陣列
- 循環上述內容直到用戶輸入「」或點擊取消。
- 將所有員工存儲到可打印到控制檯的對象中。
這就是我的代碼的樣子。
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
當我測試我的輸出,但是我得到未定義。我正在嘗試訪問特定人員的名字,但無法訪問。
當我想你的代碼,這導致打印出整個名稱,而不是僅僅的名字。即使代碼是alert(employee [1] .firstname),它也會打印John Doe而不僅僅是John。 – user3551329 2014-10-13 02:11:28
是的,你是對的!這是因爲你缺少在分割函數中添加分隔符,它應該包含一個空格:var results = input.split('');小提琴現在已經更新,你可以再試一次[link] http://jsfiddle.net/mLrdjcdp/ – 2014-10-13 02:41:00