14. We Made a Friend - Adding Object to Array

javascript

#1



https://www.codecademy.com/courses/building-an-address-book/0/6?curriculum_id=506324b3a7dffd00020bf661#

QUESTION: Why does the list print 2 duplicates of what's in my contacts array?


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"*/
function search(lastName)
{
    var contactsLength = contacts.length;
    for(q = 0; q < contactsLength; q++)
    {
        if(lastName = contacts[q].lastName)
        {
            printPerson(contacts[q]);
        }
    }
}

search("Jones");





function add(firstName, lastName, email, phoneNumber)
{
    newContact = new Object();
    newContact.firstName = this.firstName;
    newContact.lastName = this.lastName;
    newContact.email = this.email;
    newContact.phoneNumber = this.phoneNumber;
    
    contacts[contacts.length] = newContact;
}

add("Red", "Liquid", "Redliquid@gmail.com", 025250666);
list();

QUESTION: Why can't i add a new contact like above but i can do it if i write ?

contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}


#2

@redliquid,
Try it by NOT using the this keyword.....
and/or
use a console.log( this ) in the function and see what what the this keyword is referring to....

google search
+++ this explained
javascript this explained site:stackoverflow.com
http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work
https://www.codecademy.com/forum_questions/55f03d4b93767651db0005b3


#3

@leonhard.wettengmx.n thank you good sir


#4

working code
var add=function(firstName, lastName,email, phoneNumber){
contacts[contacts.length]={
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email};
};
add("xyz","abc",999,"a@daafg.com");
list(contact[2]);