简体   繁体   中英

Javascript for-in loop issue

I'm doing codecademy right now and I'm having an issue with one lesson involving for-in loops. The requirement for thi exercise is to log "bill" and "steve to the console. However, I'm getting the entire array except those two strings logged instead. What's going on here?

   var friends = {
    bill: {firstName: "Bill", 
            lastName: "Ferny",
            number: "452-556-5412", 
            address: ['One Bree Hill', 'Bree', 'Middle Earth', '00000']
           },
    steve: {firstName:"Steve",
             lastName:"Rogers",
             number:"805-223-5568",
             address: ['1500 Settlers Court', 'Paso Robles', 'CA', '93446']
             }
   };
   var list = function (friends) {
       for (var p in friends) {
    console.log(friends[p]);
    }
   };
   list(friends);

change console.log(friends[p]); into console.log(friends[p].firstName); .

In a for-in loop, the variable is set to the property names. So if you want to log the property name, use console.log(p) . friends[p] is the value that the property name maps to in the object.

You need to specify what you want even further.

This:

console.log(friends[p]);

should be changed to this:

console.log(friends[p].firstName);

Your code is only getting you all of the properties associated with friends[bill] and friends[steve] . You want their first names, so you have to use dot notation and add .firstName to the end of your console.log() statements.

As other people have noted, you can also use console.log(p) which logs the property name (so bill and steve), but since you are on Codecademy, I think they'll want you to use the first method I mentioned.

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