繁体   English   中英

JavaScript中的嵌套循环

[英]Nesting loops in javascript

我认为以下代码是正确的:

该函数应检查firstName是否是实际联系人的firstName,并且给定属性(prop)是该联系人的属性。

如果两者都为真,则返回该属性的“值”。

使用参数“ Kristian”和“ lastName”对函数lookUpProfile的调用应返回值“ Vos”,但不是。

有些想法哪里错了?

 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){ for(var i=0;i<contacts.length;i++){ for(var j=0;j<contacts[i].length;j++){ if(contacts[i][0]===firstName && contacts[i][j].hasOwnProperty(prop)){ return contacts[i][j]; } } } } // Change these values to test your function lookUpProfile("Kristian", "lastName"); 

您的代码存在的问题是,第二个for循环正在检查根本不存在的属性contacts[i].length 对象没有.length属性,只有数组。

您不需要第二个for循环即可循环所有属性,只需检查firstName,然后检查所需的属性是否存在,然后将其返回即可。

for(var i=0;i<contacts.length;i++){ if(contacts[i]['firstName']===firstName && contacts[i].hasOwnProperty(prop)){ return contacts[i][prop]; } }

应该是你想要的。


如果要循环所有对象属性,应使用for in循环,如下所示:

for(var key in contacts[i]){ //place your check here using contacts[i][key] the get the value for the key }

编辑:增加了for in例如

您仅可以在lookup-function中使用两行代码来解决问题:

function lookUpProfile(firstName, prop) {
  var contact = contacts.find((c) => c.firstName === firstName);
  return contact.hasOwnProperty(prop) ? contact[prop] : null;
}

用我的JSFiddle尝试一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM