if else 数组查找

if else array lookup

我有这样一组联系人:

var contacts = [{
  "firstName": "Akira",
  "likes": "beer",
}, // other contacts

和一个使用 if/else 进行查找的函数,调用方式如下:

lookUpProfile("Akira", "likes"); 

如果函数找到名称为 "Akira" 和 属性 "likes" 的参数,它将 return "beer"。如果找不到这样的名称,它应该 return "no such name" ,如果找不到参数 "likes" ,它将 return "no such property"

我很高兴看到您关于如何更好地编写它的建议,但修复我的代码也将是极好的。 (它 returns "undefined" 而不是 "no such contact"

function lookUpProfile(firstName, prop) {

  for (var i = 0; i < contacts.length; i++) {

    var name = contacts[i].firstName;
    var propz = contacts[i].hasOwnProperty(prop);

    if (name == firstName && propz) {
      return contacts[i][prop];
    } else if (propz !== prop && firstName == name) {
      return "no such property";
    } else if (firstName !== name && propz == prop) {
      return "no such contact";
    }
  }
}

lookUpProfile("Akira", "lastName");

谢谢!

您犯的一个错误是 hasOwnProperty return 是一个布尔值,但您将其与传入的字符串进行比较。此外,如果您从每个 if/else 块 returning,那么实际上不需要 else/if ,您可以只使用 if:

以下是您对案例的看法:

// store current contact in a variable
var contact = contacts[i];

// get properties from the current contact
var name = contact.firstName;
var propValue = contact[prop];

// check for existence of the passed in first name and property
var hasName = name === firstName;
var hasProp = contact.hasOwnProperty(prop);

// if it has both, return property
if (hasName && hasProp) {
  return propValue;
}

// if it only has the name, return 'no such prop'
if (hasName) {
  return 'no such prop';
}

// otherwise it has neither so we return 'no such contact'
return 'no such contact';

演示

var contacts = [{
  "firstName": "Akira",
  "likes": "beer",
}];

function lookUpProfile(firstName, prop) {

  for (var i = 0; i < contacts.length; i++) {
    // store current contact in a variable
    var contact = contacts[i];

    // get properties from the current contact
    var name = contact.firstName;
    var propValue = contact[prop];

    // check for existence of the passed in first name and property
    var hasName = name === firstName;
    var hasProp = contact.hasOwnProperty(prop);

    // if it has both, return property
    if (hasName && hasProp) {
      return propValue;
    }

    // if it only has the name, return 'no such prop'
    if (hasName) {
      return 'no such prop';
    }

    // otherwise it has neither so we return 'no such contact'
    return 'no such contact';
  }
}

console.log(lookUpProfile("Akira", "likes")); // beer
console.log(lookUpProfile("Akira", "something else")); // no such prop
console.log(lookUpProfile("Someone else", "likes")); // no such contact


或者,您可以使用 Array.prototype.find 按名字查找此人,然后根据 find():

的结果 return 来代替循环
// finds the person with the provided name or return undefined
var contact = contacts.find(function(c) {
  return c.firstName === firstName;
});

// if no contact exists, return 'no such contact'
if (!contact) {
  return 'no such contact';
}

// if contact doesn't have the prop, return 'no such prop'
if (!contact.hasOwnProperty(prop)) {
  return 'no such prop';
}

// otherwise return the prop value
return contact[prop];

演示

var contacts = [{
  "firstName": "Akira",
  "likes": "beer",
}];

function lookUpProfile(firstName, prop) {

  // finds the person with the provided name or return undefined
  var contact = contacts.find(function(c) {
    return c.firstName === firstName;
  });

  // if no contact exists, return 'no such contact'
  if (!contact) {
    return 'no such contact';
  }

  // if contact doesn't have the prop, return 'no such prop'
  if (!contact.hasOwnProperty(prop)) {
    return 'no such prop';
  }

  // otherwise return the prop value
  return contact[prop];
}

console.log(lookUpProfile("Akira", "likes")); // beer
console.log(lookUpProfile("Akira", "something else")); // no such prop
console.log(lookUpProfile("Someone else", "likes")); // no such contact

我猜你从 nem035 的 post 那里得到了答案。

如果您想探索另一种方式,您可能仍会看到此片段。

您可以使用filter 属性 来先筛选与名字匹配的json 对象。然后检索您通过 prop.

传递的键的值
var contacts = [
    {
        "firstName": "Akira",
        "likes": "beer",
    }]

function lookUpProfile(firstName, prop){
var _toReturn =""
//_inArray will only have matched json object
var _inArray=contacts.filter(function(item){ 
  return item.firstName = firstName;
})
if(_inArray.length !==0){
console.log(_inArray[0])
  _toReturn =_inArray[0][''+prop+''];
}
// here you can also check if key prop exist in current object
else if(_inArray.length ==0) { 
_toReturn="no such contact";
}
return _toReturn;
}
document.write('<pre>'+lookUpProfile("Akira","likes")+'</pre>')

JSFIDDLE

您的代码从不执行整个 for 循环。在循环的第一个元素上,所有选项 return something.

你的函数试图做太多事情。如果将功能拆分成更小的功能,工作起来会更好更容易。

我先拆分查找联系人的功能:

function findContact(firstName) {
    for (var i = 0; i < contacts.length; i++) {
        var name = contacts[i].firstName;

        if(name === firstName) {
            return contacts[i];
        }
    }

    // contact was not found.
    return undefined;
}


function lookUpProfile(firstName, prop) {
    var contact = findContact(firstName);

    // undefined is a falsy value
    if(!contact) {
       return "no such contact";
    }

    // no need to else because the if branch terminates the function with a return
    var propz = contact.hasOwnProperty(prop);

    if(!propz) {
        return "no such property";
    }

    // again, no need to add an else
    return contact[prop];
}

lookUpProfile("Akira", "lastName");

然后您可以使用 Array.find 的函数实现替换 findContact 函数代码,例如:

function findContact(firstName) {
    return contacts.find(function(contact) {
       return contact.firstName === firstName;
    }
}

或者,如果您的代码将 运行 用于 ES6,您可以再简化一点:

function findContact(firstName) {
    return contacts.find(contact => contact.firstName === firstName);
}

我更喜欢对数组对象使用 for in 循环。您还应该 return 循环外的结果。您可以通过 Object.keys() 获取对象键。

var contacts = [{
  "firstName": "Akira",
  "likes": "beer",
},
{
    "firstName":"Suu",
    "likes" : "computer"
}];
function lookUpProfile(firstName, prop) {

  for (var i in contacts) {
    var name = contacts[i].firstName;
    var propz = Object.keys(contacts[i])[1];    
    if (name == firstName && propz == prop) {
      result = contacts[i][prop];
    } else if (prop != propz && firstName == name) {
       result = "no such property";
    } else if (firstName !== name && prop == propz) {
       result = "no such contact";
    }
  }
  return result;
}
console.log(lookUpProfile("Suu","likes"));