尝试在对象中使用带有 if else 语句的 for 循环 [英] trying to use a for loop with if else statement in objects

查看:39
本文介绍了尝试在对象中使用带有 if else 语句的 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来遍历保存对象的变量.如果你传入一个对象属性的名字,你应该得到 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?对!它立即返回 truefalse ,根本不循环遍历剩余的条目.

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 移动到 outside 循环:

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 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆