gpt4 book ai didi

Javascript/jQuery/JSON/localStorage 游戏,无法按数字排序排名表

转载 作者:行者123 更新时间:2023-12-03 00:33:09 25 4
gpt4 key购买 nike

下面的代码为我完成的游戏创建了排行榜,我唯一无法做到的就是自动将分数从高到低排序。我想我需要将对象放入数组中,然后对它们进行排序,只是不知道如何进行。

function createLeaderboard() {
var html;
html = "<table>";
html += "<tbody>";
html += "<th>Username</th>";
html += "<th>Rank</th>";
html += "<tr>";

for(var val in localStorage){


if (localStorage.getItem(val) !== null && localStorage.getItem(val) !== localStorage.getItem('UsrLoggedIn')){
var rankData = $.parseJSON(localStorage.getItem(val));

//console.log(rankData); This will allow you to see the rank data object in your console

$(rankData).each(function() {
html += "<td>" + rankData.username + "</td>";
html += "<td>" + rankData.rank + "</td> </tr>";
});
}

}
html += "</tbody>";
html += "</table>";

$('#rank').append(html);

最佳答案

您可以先检索rankData,对其进行排序,最后循环遍历排序后的数组。

function createLeaderboard() {
var html;
html = "<table>";
html += "<tbody>";
html += "<th>Username</th>";
html += "<th>Rank</th>";
html += "<tr>";

var array = [];
for (var val in localStorage) {
if (localStorage.getItem(val) !== null && localStorage.getItem(val) !== localStorage.getItem('UsrLoggedIn')) {
array.push($.parseJSON(localStorage.getItem(val)));
}
}

array.sort(function (a, b) {
return a.rank - b.rank;
});

array.forEach(function (rankData) {
html += "<td>" + rankData.username + "</td>";
html += "<td>" + rankData.rank + "</td> </tr>";
});

html += "</tbody>";
html += "</table>";

$('#rank').append(html);
}

关于Javascript/jQuery/JSON/localStorage 游戏,无法按数字排序排名表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53772332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com