Javascript For…In syntax issue?

邮差的信 提交于 2019-12-02 09:52:31

The for in loop iterates over keys, not values.

friend is a string holding the name of each property.
To get the value, use friends[friend].

Great documentation of the for..in loop can be found on mdn. Where variable is assigned through each iteration to "a different property name".

You also may not need to loop through each friend. What if you changed your search function to use hasOwnProperty on the object:

var search = function(name) {
    if(friends.hasOwnProperty(name)){
        return friends[name];
    }
};

This would check that you have a property of name in the object friends and return it. Here's a quick EXAMPLE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!