如何确保 JavaScript 检查所有属性

how to make sure javascript check all properties

本文关键字:检查 属性 JavaScript 何确保 确保      更新时间:2023-09-26

嗨,我正在尝试检查联系人是否存在以及它是否具有特定属性,然后返回它

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) {
    var i;
    for (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";
        } else if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop) === false) {
            return "No such property";
        }
    }
}
lookUp("Harry", "likes");

问题是它只返回循环中的第一个结果,所以在这种情况下,它只会检查联系人[0] firstName===firstName,然后返回false,即使联系人[1] firstName===firstName

试试这个:

    // Returns:
    //    contact prop if: contact with prop found
    //    true if: contact found, but not prop
    //    false if: not contact found
    function lookUp(firstName, prop) {
        var i, nameFound = false;
        // Starts a loop that looks every contact until the list ends or until firstName with prop is found
        for (i = 0; i < contacts.length; i++) {
            if (contacts[i].firstName === firstName ) {
                // If found, the function return the property "prop" of the contact named "firstName"
                // Note that if there is 2 persons with the same name and both has prop, it returns the first one on the list
                if(contacts[i].hasOwnProperty(prop)){
                    return contacts[i][prop];
                }
                else{
                    nameFound = true;
                }   
            }
        }
        // If the script reach this place, it's because the person wasn't found or was found but hasn't the prop
        return nameFound;
    }
function lookUp(firstName, prop) {
    var i;
    for (i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === firstName) {
           if(contacts[i].hasOwnProperty(prop)){
              return contacts[i][prop];
            }else{
              return "No such property";
            }
        }
    }
    return "No such Contact";
}

要检查对象是否具有属性,您可以if(obj[prop]) 。我喜欢减少这种事情:

function lookUp (firstName, prop) {
    return contacts.reduce(
        function (found, contact) {
            if (contact[prop] && contact.firstName === firstName)
                found.push(contact);
            return found;
        }, []
    );
}