if else数组查找

时间:2016-07-01 14:57:45

标签: javascript if-statement contacts

我有一系列像这样的联系人:

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

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

lookUpProfile("Akira", "likes"); 

如果函数同时找到名称为"Akira"的参数和属性"likes",则会返回"beer"。如果找不到此名称,则应返回"no such name",如果找不到参数"则喜欢"它将返回"no such property"

我很高兴看到你关于如何更好地编写它的建议,但修复我的代码也会很棒。 (它返回"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");

谢谢!

4 个答案:

答案 0 :(得分:2)

您犯的一个错误是hasOwnProperty返回一个布尔值,但您将它与传入的字符串进行比较。另外,如果您从每个if/else块返回,那么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';

演示

&#13;
&#13;
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
&#13;
&#13;
&#13;

或者,您可以使用Array.prototype.find代替循环,而不是循环来查找人名,然后根据find()的结果返回:

// 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];

演示

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我猜你从nem035的帖子中得到了答案。

如果您想探索其他方式,可能仍会看到此片段。

您可以使用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

答案 2 :(得分:0)

您的代码永远不会执行整个for循环。在循环的第一个元素上,所有选项都会返回一些内容。

你的功能是尝试做太多事情。如果将功能拆分为较小的功能,那么工作会更好更容易。

我首先要分割寻找联系人的功能:

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);
}

答案 3 :(得分:0)

我更喜欢对数组对象使用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")); 获取对象密钥。

SELECT players.codsw
      ,sessions.userid
      ,sessions.idlocation
      ,location.denomination
  FROM sessions sess
      ,location loc
      ,players  pl
 WHERE location.idlocation = sessions.idlocation
   AND players.userid = sessions.userid
   AND players.codsw IN ('MEGA SHOW', 'ANCORINA')
   AND EXISTS (SELECT sessions.idlocation
              ,COUNT(*)
          FROM sessions
              ,location
              ,players
         WHERE location.idlocation = sessions.idlocation
           AND players.userid = sessions.userid
           AND players.codsw IN ('MEGA SHOW', 'ANCORINA')
           AND sessions.idlocation = sess.idlocation
         GROUP BY sessions.idlocation
        HAVING COUNT(*) > 1)
 ORDER BY location.denomination