简体   繁体   English

JavaScript中的嵌套循环

[英]Nesting loops in javascript

I think the code below is correct: 我认为以下代码是正确的:

The function should check if firstName is an actual contact's firstName and the given property (prop) is a property of that contact. 该函数应检查firstName是否是实际联系人的firstName,并且给定属性(prop)是该联系人的属性。

If both are true, then return the "value" of that property. 如果两者都为真,则返回该属性的“值”。

The call to the function lookUpProfile with the arguments "Kristian" and "lastName" should return the value "Vos" but it is not. 使用参数“ Kristian”和“ lastName”对函数lookUpProfile的调用应返回值“ Vos”,但不是。

Some idea where is wrong? 有些想法哪里错了?

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

The problem with your code is that the second for loop is checking for a property contacts[i].length that simply doesn't exists. 您的代码存在的问题是,第二个for循环正在检查根本不存在的属性contacts[i].length Objects don't have a .length property, only Arrays. 对象没有.length属性,只有数组。

You don't need a second for loop to cycle all the properties, you can just check the firstName and then check if the property you want is there, then return it. 您不需要第二个for循环即可循环所有属性,只需检查firstName,然后检查所需的属性是否存在,然后将其返回即可。

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

Should be what you want. 应该是你想要的。


If you want to cycle all the object properties you should use a for in loop like this: 如果要循环所有对象属性,应使用for in循环,如下所示:

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

Edit: added for in example 编辑:增加了for in例如

You could solve your problem only with two lines of code in your lookup-function: 您仅可以在lookup-function中使用两行代码来解决问题:

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

Try it out with my JSFiddle . 用我的JSFiddle尝试一下。

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

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