为什么以下javascript代码会打印三次结果?

时间:2014-05-24 12:27:10

标签: javascript

“steve”联系人在控制台中打印三次。

var friends = {
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "555555555",
        address: ["One Infinite Loop", "Cupertino", "CA", "98052"]
    },
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "555555555",
        address: ["One Microsoft way", "Redmond", "WA", "98052"]
    }
};

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

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

说明:定义一个带有单个参数name的函数搜索。如果传递给函数的参数与朋友中的任何名字匹配,它应该将该朋友的联系信息记录到控制台并返回它。

1 个答案:

答案 0 :(得分:0)

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

它是胜利的桥梁......试试吧!