将对象添加到现有对象数组-JavaScript [英] Adding objects to an existing array of objects - JavaScript

查看:63
本文介绍了将对象添加到现有对象数组-JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个由2个对象组成的数组,我希望编写一个添加"功能来动态地向该数组中添加更多的人.

I've created an array of 2 objects, and I wish to write an 'add' function to dynamically add more people to this array.

您能解释一下为什么下面的添加"功能不能将对象成功添加到联系人"数组中吗?

Can you explain why the 'add' function below does not add an object to the 'contacts' array successfully.

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];
var contactsLength = contacts.length;

function add (firstName, lastName, phoneNumber, email) {
    contacts[contactsLength] = {
        firstName: firstName,
        lastName: lastName,
        phoneNumber: phoneNumber,
        email: email
    };
};


function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
    for (var i = 0; i < contactsLength; i++) {
        printPerson(contacts[i]);
    }
}

add("MJ", "Foster", "MJ@gmail", "714-333-5555");

list();

推荐答案

您的代码无法正常运行的原因是因为以下这一行:

The reason your code isn't working the way you think it should is because of this line:

var contactsLength = contacts.length;

在这里,您将contacts.length的值分配给变量contactsLength,但是此后,即使contacts数组的大小发生变化,contactsLength也不会发生变化.

Here, you're assigning the value of contacts.length to the variable contactsLength, but thereafter, contactsLength will not change even if the size of your contacts array changes.

相反,您应该只引用属性contacts.length.

Instead, you should simply refer to the property contacts.length.

这是您的代码的更正版本:

Here is a corrected version of your code:

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function add (firstName, lastName, phoneNumber, email) {
    contacts[contacts.length] = {
        firstName: firstName,
        lastName: lastName,
        phoneNumber: phoneNumber,
        email: email
    };
};


function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
    for (var i = 0; i < contacts.length; i++) {
        printPerson(contacts[i]);
    }
}

add("MJ", "Foster", "MJ@gmail", "714-333-5555");

list();

请注意:使用本机数组方法push(),将执行与contacts[contacts.length] = {...}完全相同的操作.

Please note: using the native array method push(), would do exactly the same same thing as contacts[contacts.length] = {...}.

这篇关于将对象添加到现有对象数组-JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆