问题
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();
回答1:
Try to use push method
function add (firstName, lastName, phoneNumber, email) {
var newContact = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
};
contacts.push(newContact);
};
回答2:
The reason your code isn't working the way you think it should is because of this line:
var contactsLength = contacts.length;
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.
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();
Please note: using the native array method push()
, would do exactly the same same thing as contacts[contacts.length] = {...}
.
回答3:
Your Add function works fine, although a better way would be to use a push() method as per @MysterX as keeping a track of array index might not always prove very reliable especially if you are using public variable for tracking it. push() method
Your error is in your printPerson function. Have a closer look on your for loop and change it a bit into this
function list() {
for (var i = 0; i <= contactsLength; i++) {
printPerson(contacts[i]);
}
}
and see if you can spot the error...
Hope this helps.
来源:https://stackoverflow.com/questions/32580067/adding-objects-to-an-existing-array-of-objects-javascript