简体   繁体   中英

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.

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.

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. Objects don't have a .length property, only Arrays.

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(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(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

You could solve your problem only with two lines of code in your 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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