重构查找函数

Refactoring Lookup Function

本文关键字:函数 查找 重构      更新时间:2023-09-26

我试图重构这个函数,但遇到了麻烦。该函数试图实现的是查找JSON对象中是否存在联系人,如果存在,则确定提供的第二个参数是否是指定对象上存在的属性。

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){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
   if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
   }
}
  for (var j = 0; j < contacts.length; j++) {
   if (contacts[j].firstName !== firstName) {
      return "No such contact";
   } else if (!contacts[j].hasOwnProperty(!prop)) {
      return "No such property" ; 
   }
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("kyle", "lastName");

filter找出所有匹配项,如果找到其他属性,则返回true false

function lookUpProfile(firstName, prop) {
  var list = contacts.filter(function (el) {
    return el.firstName === firstName;
  });
  return list.length && list[0][prop] ? true : false;
}
lookUpProfile("kyle", "lastName"); // false
lookUpProfile("Akira", "lastName"); // true
lookUpProfile("Akira", "password"); // false

演示

不需要像现在这样循环两次函数。快速更改会给你这样的东西:

function lookUpProfile(firstName, prop){
    var nameFound = false;
    for (var i = 0; i < contacts.length; i++) {
        var contact = contacts[i];
        // if a correct name is found, store that
        if(contact.firstName === firstName){
            nameFound = true;
            if(contact.hasOwnProperty(prop)) {
                return contact[prop];
            }
        }                
    }
    return nameFound ? "No such property" : "No such contact";
}

基本上,你只需要在找到特定名称的过程中添加一个复选框。如果属性存在,函数将返回对象,但如果它恰好到达末尾(找不到匹配项),则可以知道是否找到了名称。

这假设您只想返回找到的第一个匹配项。

我不确定你想做什么。函数报告这两种情况的唯一方法是让它返回一个带有结果的对象。试试这个。

function lookUpProfile(firstName, prop){
// Only change code below this line
    var result ={contactExist: false, secondParameter:false};
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === firstName) {
            result.contactExists=true;
           result.secondParameter= contacts[i][prop]!=null;
            return result;
        }
    }
    return result;
// Only change code above this line
}