6. Stuck trying to add to array the new contact


#1

This is the code, please help:

`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 printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

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

/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
var contactsLength = contacts.length;
for (i = 0 ; i < contactsLength ; i++) {
if ( lastName === contacts[i].lastName) {
printPerson(contacts[i]);
}
}
};

var add = function(firstName, lastName, email, phoneNumber) {
var alex = new Object();
alex.firstName = firstName;
alex.lastName = lastName;
alex.email = email;
alex.phoneNumber = phoneNumber;
};

contacts[contacts.length] = add("Alex", "Test", "test@gmail.com", "07451234567");

list();
`

What am I doing wrong?


#2

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

#3

i give up, the error message keeps saying "syntax error:unexpected token".

var add = function ( firstName, lastName, email, phoneNumber); contacts =[contact.length] = {
firstName: dave,
lastName : crosby,
email : davecrosby@example.net,
phoneNumber : 07815678876;
};

};

var contacts[contacts.length]=add ("dave", "crosby","davecrosby@example.net","07815678876");

i think i may have the contact function at the bottom incoorect, can someone verify this for me ?

thanks.


#4

Here's my code which worked:

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 printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

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

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

add("Charlie", "Vaitkevicius", "hello@yahoo.com", "248-666-3857");

list("Charlie");

What confuses me is that one of the directions said to "Add this new contact object to the contacts array," and I wasn't sure what that meant. I ignored that though.


#5

Take a good look at this line of your code compare it to what i provided earlier and you will see the error