Object.keys forEach循环读取整个对象

时间:2015-09-23 20:17:40

标签: javascript jquery foreach

我有一个充满数组的对象叫做“玩家”#39;每个包含5个名字。我想在读完所有5个后循环并停止,但是这段代码只读取整个对象而不是5个。

$(function () {
    var $playerSubMenu = $("li.teams ul.sub_menu li");
    var $playerAdd = "";
    $playerAdd += "<ul>";
    Object.keys(team).sort().forEach(function (a) {
        for (var i = 0; i < team[a].player.length; i++) {
            var $players = "<li><a href=\"#\">" + team[a].player[i] + "</a></li>";
            $playerAdd += $players;
        }
    });
    $playerAdd += "</ul>";
    $($playerSubMenu).append($playerAdd);
});

这是&#39;团队的一小部分&#39;这个jQuery来自的对象:

c9: {id: "8", team: "Cloud9", player: ["n0thing", "seang@res", "shroud", "Skadoodle", "freakazoid"], country: "USA"},

Here is a picture illustrating what is going wrong

我的计划是为每位玩家添加一个列表项,但最终发生的事情是我得到100个列表项(每个&#39;玩家&#39;在&#39;团队&#39;对象中)。我试过了:

Object.keys(team).sort().every(function (a) {
    same code as above...
)};

每个团队中假冒的第6名玩家都是“假”,这适用于第一个列表项,但接下来是每一个&#34; Team&#34;列表项与前5名玩家完全相同。

1 个答案:

答案 0 :(得分:0)

$playerAdd += "<ul>";$playerAdd += "</ul>";移至Object.keys(team).sort().forEach(function (a) { here });

的区块代码
Object.keys(team).sort().forEach(function (a) {
    $playerAdd += "<ul>";
    for (var i = 0; i < team[a].player.length; i++) {
        var $players = "<li><a href=\"#\">" + team[a].player[i] + "</a></li>";
        $playerAdd += $players;
    }
    $playerAdd += "</ul>";
});