我正在执行上面引用的活动,其中程序需要按姓氏搜索条目,找到该条目,然后返回与姓氏匹配的所有条目的名字和姓氏。 可以找到活动here。
我的代码在运行后显示正确的消息(Bob Jones),但它附带一条错误消息:" TypeError:无法读取属性' lastName'未定义"
我无法弄清楚错误消息的来源,以及如何解决它。欢迎提出任何意见。
我的代码:
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) {
for (var i = 0; i <= contacts.length; i++) {
if (contacts[i].lastName === lastName) {
printPerson(contacts[i]);
}
}
};
search("Jones");
答案 0 :(得分:1)
for
中的search()
循环循环次数过多。
你在list()
中做得对,但在search()
中,你犯了一点错误。
你有:
for (var i = 0; i <= contacts.length; i++) {
应该是:
for (var i = 0; i < contacts.length; i++) {
答案 1 :(得分:0)
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];
// printPerson added here
var printPerson = function(person){
console.log(contacts[0].firstName + " " + contacts[0].lastName);
console.log(contacts[1].firstName + " " + contacts[1].lastName);
};
printPerson(contacts[0]);
printPerson(contacts[1]);
答案 2 :(得分:-1)
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777 FREE",
email: "bob.jones@example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888 FREE",
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 search(lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if (lastName === contacts[i].lastName) {
printPerson(contacts[i]);
};
};
};
search("Jones");
function add(firstName, lastName, email, phoneNumber){
object = {
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber
};
contacts[contacts.length] = object;
};
add("firstName", "lastName", "name@example.com", "32874683275");
list();