JavaScript - Array_Push()的有线行为

时间:2014-12-22 00:26:37

标签: javascript arrays

我有一个奇怪的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': 'example@mail.com'}],
            address: 'Some Streetz 2.',
            city: 'Las Vegas',
            notes: 'Napomena',
        },
        {
            id: 1,
            firstName: 'Mike',
            lastName: 'Smith',
            phones: [{'phone1':'111111'}],
            emails: [{'email1': 'example@mail.com'}],           
            address: '459 5th Av.',
            city: 'New York',
            notes: 'Napomena',
        }
    ];

将数组添加到contacts数组

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);

    };

1 个答案:

答案 0 :(得分:2)

contacts.length++增加了数组的长度,基本上等于contacts.push(undefined)。然后你添加另一个元素。

contact.id = contacts.length是正确的选择。如果你需要一个大于长度的" (你不会这样),contact.id = contacts.length + 1是写它的正确方法。