我正在Codecademy学习 JavaScript 课程。在这个练习中,我们应该创建一个函数add
来将一个人添加到contacts
数组中,然后使用提示从用户那里获取信息,然后我们调用该函数list
将数组中的所有人打印contacts
到控制台.
当我运行下面的代码时,它会列出contacts
数组中的两个现有人员,然后打印"undefined undefined"
出我尝试使用提示添加的人员。但是,当我打印 的长度时contacts
,它会显示3
,因此添加了一个人。
任何帮助将不胜感激。
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 = new Array(bob, mary);
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}
function list() {
var length = contacts.length;
var i;
for (i = 0; i < length; i++) {
printPerson(contacts[i]);
}
}
/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
var number = contacts.length;
for (i = 0; i < number; i++) {
if (contacts[i].lastName === lastName) {
printPerson(contacts[i]);
}
}
};
var add = function(firstName, lastName, email, telephone) {
contacts[contacts.length] = new Object(firstName, lastName, email, telephone);
};
var firstName = prompt("What is your first name");
var lastName = prompt("What is your last name");
var email = prompt("What is your email");
var telephone = prompt("What is your phone number");
add(firstName, lastName, email, telephone);
list();