【发布时间】:2021-05-19 02:14:38
【问题描述】:
我正在学习网络开发,我尝试做这个练习,但给出的答案与我的不同。可能,任何人都请帮我看看我的错误是什么。
代码如下:
给出的答案:
// Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
];
function lookUpProfile(name, prop){
// Only change code below this line
for (let x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}
lookUpProfile("Kristian", "lastName");
我的回答:
function lookUpProfile(name, prop) {
// Only change code below this line
for (let i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else if (!contacts[i].firstName) {
return "No such contact";
} else {
return "No such property.";
}
}
// Only change code above this line
}
调用lookUpProfile("Kristian", "lastName") 应该返回字符串Vos。
【问题讨论】:
-
因为你总是在 for 循环中返回,所以它永远不会检查超过第一条记录(你的函数将适用于“Akira”),仅此而已。所以,你的错误是永远不允许循环继续。
return将结束循环并结束函数。
标签: javascript arrays function