2014-10-12 81 views
0

假設你有一個對象如何在Javascript中動態插入和訪問對象中的對象?

var employee = []; 

你將如何提示(與提示功能)用戶輸入信息,使得它看起來像這樣:

var employee = [ 
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter", "lastName": "Jones"} 
]; 

當然有數目不詳的陣列。所以,如果你的用戶只輸入一個員工的信息,然後輸入什麼或命中取消數組將只有一個數組(對於John Doe)。

但主要的是用戶輸入信息,直到他們決定完成。所以沒有指定數量的數組。

我需要用循環提示來做到這一點,即使我明白提示吸吮。很多。

因此,這裏是我想要做的事:

  1. 爲僱員提示用戶。示例輸入:John Doe
  2. 取字符串,使用分割函數。之後,您將有一個名爲John Doe的陣列
  3. 循環上述內容直到用戶輸入「」或點擊取消。
  4. 將所有員工存儲到可打印到控制檯的對象中。

這就是我的代碼的樣子。

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 

當我測試我的輸出,但是我得到未定義。我正在嘗試訪問特定人員的名字,但無法訪問。

回答

2

你可以像下面這樣做

var flag = true, arr = []; 
while (flag) { 
    arr.push({ 
     firstname: prompt("What's your first name?") || "John", 
     lastname: prompt("What's your last name?") || "Doe" 
    }); 
    flag = confirm("Do you want to continue?"); 
} 

要不,你也可以做

var arr = (prompt("What's your name with first and last name") || "John Doe").split(" "); 
arr.push({ 
    firstname: arr[0], 
    lastname: arr[1] 
}); 
1

你打電話分裂(),但沒有提供任何參數。如果它是一個名字,我假設第一個和最後一個被空格分開。它應該是這樣的:

var results = input.split(" "); 
0

他們的建議都是正確的。

而且爲什麼你的代碼不能正常工作的原因是因爲你只有對象的單個實例,以及所有你的員工陣列的參考值這個人對象。 一旦你輸入「」,你的person對象屬性有一個未定義的值,所以你的employee數組中的值也是未定義的。

您可以修改person對象爲多個實例來修復此錯誤。

function person() { 
      return {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 
      per = person(); 

      per.firstname = results[0]; 
      per.lastname = results[1]; 

      employee[i] = per;//store the person array into the customer array. 
     } 

     console.log('hi'); 
     console.log(employee[1].firstname); 

fiddle here

+0

當我想你的代碼,這導致打印出整個名稱,而不是僅僅的名字。即使代碼是alert(employee [1] .firstname),它也會打印John Doe而不僅僅是John。 – user3551329 2014-10-13 02:11:28

+0

是的,你是對的!這是因爲你缺少在分割函數中添加分隔符,它應該包含一個空格:var results = input.split('');小提琴現在已經更新,你可以再試一次[link] http://jsfiddle.net/mLrdjcdp/ – 2014-10-13 02:41:00