这是codeacademy项目的一部分。从开头到列表的部分();功能或多或少都有效。我的任务是使用for循环创建搜索功能。 提前谢谢。
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);
}
var list = function(){
var contactsNumber = contacts.length;
for(i=0; i<=contactsNumber; i++){
printPerson(contacts[i]);
}
};
list();
var search = function(lastName){
var number = contacts.length;
for(i=0; i<= number; i++){
if(lastName === contacts[i].lastName){
printPerson(contacts[i]);
}
}
};
search("Jones");
答案 0 :(得分:2)
如果数组中有2个项目,则需要循环索引0
和1
,而不 2
。因此,请使用<
代替<=
:
for(var i = 0; i < number; i++)
答案 1 :(得分:2)
该练习被窃听(或者不知道是否修复了它)你必须运行所有其他功能才能使其正确:
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);
}
var list = function ()
{
var contactsNum = contacts.length;
for (i=0; i < contactsNum; i++)
printPerson(contacts[i]);
};
function search(lastName){
var items = contacts.length;
for(i = 0; i < items; i++){
if(contacts[i].lastName == lastName)
printPerson(contacts[i]);
}
}
list();
search("Jones");
答案 2 :(得分:0)
由于您使用了var
个关键字,因此无法访问该功能中的联系人。在联系人之前移除var
关键字,它应该可以正常工作。
答案 3 :(得分:0)
var personList = [
{ 'FirstName' : "John", 'LastName': "Doe"},
{ 'FirstName' : "Jane", 'LastName': "Deen"}
]
function PersonSearchService() {
this.Print = function(person) {
console.log(person.FirstName + " " + person.LastName);
}
this.Search = function(lastName) {
for(var p in personList) {
if(personList[p].LastName === lastName) {
this.Print (personList[p]);
}
}
}
}
var p = new PersonSearchService();
p.Search ("Doe");
你可以试试这种方式