Profile Lookup分享一下为后来人做参考
Challenge Profile Lookup has an issue.
User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.
My code:
//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 lookUp(firstName, prop){
// Only change code below this line
for(var i = 0;i < contacts.length; i++){
if(firstName == contacts[i].firstName){
if(contacts[i][prop]){
return contacts[i][prop];
}else{
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUp("Akira", "likes");
请不要在issue直接发答案来当做分享。如果你想去帮助其他人,可以去考虑写wiki和贡献给现有任务 #195 #207 。
为什么 return "No such contact"; 要放在for循环外呢
为什么 return "No such contact"; 要放在for循环外呢
我一开始也想不通。 如果return "No such contact"; 放在for循环内,那么lookUp("Akira", "likes");是可以成功返回数组的。 而Harry分明是有likes数组的,lookUp("Harry", "likes");返回的却是No such contact。 这是因为代码是从上到下执行的,for循环会把这段代码执行4次,而第一次都不匹配的话就会return “No such contact”,结束循环,不会执行第二次了。 希望我解释的足够明白。