问题描述
我正在尝试编写一个函数,该函数将通过一个包含对象的变量进行迭代.如果传入的是对象属性的名字,则应该为true.如果不是,您应该得到错误.但是,无论我通过什么功能,我总会得到错误的结果.任何帮助将不胜感激.
I'm trying to write a function that will iterate through a variable holding objects. If you pass in a first name that is an object property, you should get true. If not, you should get false. However, no matter what I pass through the function, I always get false. Any help is greatly appreciated.
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 attempt(firstName){
for(var i = 0;i < contacts.length; i++){
if(contacts[i].firstName==firstName){
return true;
} else {
return false;
}
}
}
推荐答案
仔细思考一下逻辑:在第一个循环中会发生什么?函数对 if
/ else
的响应是什么?正确的!它会立即返回 true
或 false
,而不会循环浏览其余条目.
Think through the logic for a moment: What happens on the first loop? What does the function do in response to the if
/else
? Right! It returns true
or false
right away, without looping through the remaining entries at all.
您需要完全删除 else
,然后将 return false
移到外部循环中:
You need to remove the else
entirely and move return false
to outside the loop:
function attempt(firstName) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == firstName) {
return true;
}
}
return false;
}
旁注: Array#some
正是为此用例而设计的:
Side note: Array#some
is designed for exactly this use case:
function attempt(firstName) {
return contacts.some(function(entry) {
return entry.firstName == firstName;
});
}
这篇关于尝试在对象中的if else语句中使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!