2014-12-22 18 views
-2

我有一個奇怪的Array_Push()行爲。我將數組添加到預定義的數組中。問題是由於某種原因,當我將數組推到預定義數組時,陣列的長度增加了兩個。JavaScript - Array_Push()的有線行爲

這裏是代碼:

實例陣列:

Object {id: 2, firstName: "First name", lastName: "Last name", phones: Array[0], emails: Array[0]…}$$hashKey: "00A"address: "Street 3"city: "Washington "emails: Array[0]firstName: "First name"id: 2lastName: "Last name"notes: "No notes"phones: Array[0]__proto__: Object 

JavaScript的:

var contacts = [ 
     { 
      id: 0, 
      firstName: 'John', 
      lastName: 'Doe', 
      phones: [{'phone1': '222222222'}], 
      emails: [{'email1': '[email protected]'}], 
      address: 'Some Streetz 2.', 
      city: 'Las Vegas', 
      notes: 'Napomena', 
     }, 
     { 
      id: 1, 
      firstName: 'Mike', 
      lastName: 'Smith', 
      phones: [{'phone1':'111111'}], 
      emails: [{'email1': '[email protected]'}],   
      address: '459 5th Av.', 
      city: 'New York', 
      notes: 'Napomena', 
     } 
    ]; 

添加陣列觸點陣列

this.addContact = function (contact) { 

     alert (contacts.length);//output is 2 
     contact.id = contacts.length ++;//getting ID od new array 
     console.log(contact);// 
     contacts.push(contact); 
         alert ("++"+contacts.length);//output is 4 

       console.log(contacts); 

    }; 
+0

不要在長度屬性上使用一元'++'! –

+0

作爲一個猜測,我會說你閱讀一些教程,包括增加長度計數器,每當你添加一個元素,但JavaScript陣列的內部實現爲我們照顧這個。不需要去長度++,當你操作數組時,例如使用push(),數組會自動更新長度屬性。 –

+0

你是對的@ DanielA.White。阿馬丹建議在評論中,我修正了這個錯誤。 – jureispro

回答

2

contacts.length++增加了樂數組的整數,基本相當於contacts.push(undefined)。然後你添加另一個元素。

contact.id = contacts.length是正確的選擇。如果你需要「比長度大一點」(你不這樣做),contact.id = contacts.length + 1將是寫它的正確方法。