Codecademy联系人列表输出格式

时间:2016-09-02 12:30:50

标签: javascript object

var friends = {
    bill:{
        firstName:"Bill",    
        lastName:"Gates",
        number:"(206) 555-5555",
        address: ["One Microsoft Way","Redmond","WA","98052"]
},
steve:{
       firstName:"Steve",   
       lastName:"Jobs",
       number: "(408) 555-5555",
       address: ['1 Infinite Loop','Cupertino','CA','95014']
   }
}

var list = function(friends) {
    for(var name in friends) {
    console.log(name);   
    }
};

var search = function(tname) {
    for(var name in friends) {
        if(friends[name].firstName == tname) {
            console.log(friends[name])
            return (friends[name])
        }
    }
};

这是我在联系人列表Assignment

结束时所考虑的代码

然后他们问我是否可以将其输出为

First Name: Steve
Last Name: Jobs
Number: (408) 555-5555
Address: 1 Infinite Loop
        Cupertino, CA 95014

我不知道从哪里开始 到目前为止,我只知道本教程中学到的javascript,但如果解决方案需要外部函数......我们将非常感谢您的简短描述

2 个答案:

答案 0 :(得分:0)

var friends = {
    bill: {
    firstName: "Bill",
    lastName: "Gates",
    number: "(513) 555-5555",
    address: ["Somewhere", "Over the Rainbow"]
    },
steve: {
    firstName: "Steve",
    lastName: "Jobs",
    number: "(513) 555-5555)",
    address: ["Way up", "High"]
    }
};

var list = function (obj){
for(var key in obj){
console.log(key);
}
};

var search = function(name){
for(var key in friends){
    if(friends[key].firstName === name){
        console.log(friends[key]);
        return friends[key];
    }
    }
};

你去:)

答案 1 :(得分:0)

你是对的,你有匹配的朋友对象,你应该做的是访问该对象的属性。

要访问对象的属性,可以使用点运算符或传递数组中的值,看看下面的例子

   var bill = {
       firstName:"Steve",   
       lastName:"Jobs",
       number: "(408) 555-5555",
       address: ['1 Infinite Loop','Cupertino','CA','95014']
   }

用于访问bill对象的属性

    >>> bill.firstName
    >>> Steve
    >>> bill.firstName = "John";

通过这种方式,您可以访问该属性。

一旦您访问该属性打印欲望输出,如

     >>> console.log("FirstName: "+bill.firstName);

希望这会有所帮助:)