我怎么能压缩/优化这段代码(jQuery)?

时间:2015-04-24 01:26:32

标签: javascript jquery dry

我希望优化此代码,希望占用更少的空间。我是JavaScript和jQuery的新手,所以我不太清楚它是如何完成的。

rankedSolo5["Wins"] = jsonData.playerStatSummaries[5].wins;
$("#rankedWinsSolo5 .statsValue").html(rankedSolo5["Wins"]);

rankedSolo5["Assists"] = jsonData.playerStatSummaries[5].aggregatedStats.totalAssists;
$("#rankedAssistsSolo5 .statsValue").html(rankedSolo5["Assists"]);

rankedSolo5["Kills"] = jsonData.playerStatSummaries[5].aggregatedStats.totalChampionKills;
$("#rankedKillsSolo5 .statsValue").html(rankedSolo5["Kills"]);

rankedSolo5["MinKills"] = jsonData.playerStatSummaries[5].aggregatedStats.totalMinionKills;
$("#rankedMinKillsSolo5 .statsValue").html(rankedSolo5["MinKills"]);

rankedSolo5["NeutralMinKills"] = jsonData.playerStatSummaries[5].aggregatedStats.totalNeutralMinionsKilled;
$("#rankedNeutralMinKillsSolo5 .statsValue").html(rankedSolo5["NeutralMinKills"]);

rankedSolo5["TurretsKilled"] = jsonData.playerStatSummaries[5].aggregatedStats.totalTurretsKilled;
$("#rankedTurretsKilledSolo5 .statsValue").html(rankedSolo5["TurretsKilled"]);

1 个答案:

答案 0 :(得分:4)

使用将rankedSolo5中的属性名称与aggregatedStats中的属性名称相关联的对象:

var fields = {
    "Wins": "wins",
    "Assists": "totalAssists",
    "Kills": "totalChampionKills",
    ...
};

然后你可以遍历它以执行相同的操作:

$.each(fields, function(rankedProp, statsProp) {
    rankedSolo5[rankedProp] = jsonData.playerStatSummaries[5][statsProp];
    $("#ranked" + rankedProp + "Solo5 .statsValue").html(rankedSolo5[rankedProp]);
});