【发布时间】:2016-07-08 10:18:31
【问题描述】:
在循环中我不确定我是否犯了错误或错误的代码。当我单独运行 if 语句时,它可以工作。但是当我将它与“else if”语句一起运行时。 if 语句失败,else if 语句有效,即使第一个 if 语句为真。
https://www.freecodecamp.com/challenges/profile-lookup
//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(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
if ( contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop) ) {
return contacts[i][prop];
} else if( contacts[i].firstName !== firstName ) {
return "No such contact";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
【问题讨论】:
标签: javascript loops object if-statement