简体   繁体   中英

Why am I only able to print one object in javascript?

Doing some practice runs on codecademy, and came across the following problem:

I am able to only console.log "Steve Jobs" and all his info, but I want to also

include "Bill Gates." If anyone knows how to do this that would be great, or

any alternatives to the following code:

var friends = {};

friends.bill = {
    firstName: "Bill",
    lastName: "Gates",
    number: "(206)555-5555",
    address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
};


friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "(206)777-7777",
    address: ['Apple Rd.', 'Cupertino', 'CA', '90210']
};

var list = function(list) {

    for (var dale in friends) {
        console.log(dale);
    }

}

var search = function(name) {
    for (var key in friends) {

        if (name === friends[key].firstName) {
            console.log(friends[key]);
            return friends[key];
        }
    }
};

OK, so when I run this code, only Steve gets printed. It should also print Bill.

Copy/pasted the code in the console and calling:

search('Bill');

Works just fine for me, how are you using this code?

Created a JSBin from your code with the addition that I called list(); right at the end. If you run the code using CMD+Enter you will see that the output is as expected, printing out both bill and steve

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