javascript中搜索功能中的错误

时间:2016-01-18 15:16:22

标签: javascript function search

我正在尝试返回“steve”的联系信息,但是codecademy告诉我它没有正确返回。

  

看起来您的搜索功能不会返回Steve的联系信息。

我无法在此代码中找到任何错误。你能帮我找到你能看到的搜索功能中的任何语法或逻辑错误吗?

var friends = {
    bill: {
        firstName: "bill",
        lastName: "gates",
        number :21415,
        address: ["mcklsn", "wcnskln"]
    },
    Steve: {
        firstName: "bill",
        lastName: "gates",
        number: 21415,
        address: ["mcklsn", "wcnskln"]
    }
};

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

    for (steve in friends)
        console.log(steve);
};

var search = function(name)
{
    for (var i in friends)
    {
        if (friends[i].firstName === name)
        {
            console.log(friends[i]);
            return friends[i];
        }
        else
            console.log("contact doesn't exist!");
    } 
};

2 个答案:

答案 0 :(得分:1)

你应该注意你所写的内容,不要盲目地按Ctrl-C Ctrl-V一切。你没有用正确的名字给你的friends打电话,如果有人这样对我,我会被冒犯。哎呀,如果你叫比尔,史蒂夫乔布斯会愤怒

这应该有效:

var friends = {
    Bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: 21415,
        address: ["mcklsn", "wcnskln"]
    },
    Steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: 21416,
        address: ["mcklsnn", "wcnsklnn"]
    }
};

search("Bill");
search("Steve");

答案 1 :(得分:0)

是的,因为您的Steve属性对象的firstName设置为"bill"

所以代码,搜索匹配'史蒂夫'在firstName属性上找不到...因为没有。这两个对象都有' bill'作为他们的firstName财产。