Hi I have been trying to learn Javascript using codeacademy.com and I have reached an exercise that doesn't seem to make any sense when why the exercise I have written.This is my code:
(function(){
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 printPerson = function(person){
console.log(person.firstName + " " + person.lastName);
}
var list = function(){
var i = contacts.length;
for(var j= 0; j < i ; j++){
printPerson(contacts[i]);
}
};
list();
})();
The problem is in the list function when I try to call the printPerson() function I get that person is undefined but if I write instead of the list() function this:
printPerson(contacts[0]);
printPerson(contacts[1]);
Everything works.What am I doing wrong in the list() function that it doesn't work?
var list = function(){
var i = contacts.length;
for(var j= 0; j < i ; j++){
printPerson(contacts[i]);
}
};
i
here is a constant. If you replace it:
var list = function(){
var i = contacts.length;
for(var j= 0; j < contacts.length ; j++){
printPerson(contacts[contacts.length]);
}
};
For all arrays arr
, arr[arr.length]
will always be undefined. You probably want contacts[j]
.
for(var j= 0; j < i ; j++){
printPerson(contacts[i]); // this should be contacts[j]
}
contacts.forEach(function(contact) {
printPerson(contact);
});
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];
console.log(mary.phoneNumber);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.