这是自由代码阵营中的赋值,这是我的代码,对于第一次迭代时0的循环停止,它没有完成for循环的第一次迭代的原因是真的,我怎么能强制这个代码到完成循环以检查这个对象数组'整体属性和价值观?
//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) {
debugger;
// Only change code below this line
for (var x = 0; x < contacts.length; x++) {
if (!contacts[x].hasOwnProperty(prop)) {
return 'No such property';
}
if (contacts[x].firstName != firstName) {
return 'No such contact';
}
if (contacts[x].hasOwnProperty(prop) && contacts[x].firstName === firstName) {
return prop;
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Harry", "likes");
答案 0 :(得分:2)
在循环内部,只有匹配时才应return
。否则你应该继续:
当你到达循环的末尾时,这意味着没有匹配,你可以返回一个特定的错误值:
function lookUpProfile(firstName, prop) {
debugger;
// Only change code below this line
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].hasOwnProperty(prop) && contacts[x].firstName === firstName) {
return prop;
}
}
return 'No such contact';
// Only change code above this line
}