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

Posted

技术标签:

【中文标题】Javascript/jQuery/JSON/localStorage 游戏,无法按数字排序排名表【英文标题】:Javascript/jQuery/JSON/localStorage Game, Trouble sorting ranking table numerically 【发布时间】:2019-05-15 06:55:01 【问题描述】:

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

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);

【问题讨论】:

Sorting an array of javascript objects的可能重复 Lodash 对此也有好处:***.com/questions/22928841/… 【参考方案1】:

您可以先检索rankData,然后再检索sort,最后循环排序后的数组。

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 游戏,无法按数字排序排名表的主要内容,如果未能解决你的问题,请参考以下文章