【问题标题】:Firebase Leaderboard SortingFirebase 排行榜排序
【发布时间】:2024-12-08 07:15:01
【问题描述】:

我正在尝试使用 firebase 制作排行榜,但我希望它根据点数进行排序,例如

  1. 200分
  2. 50分
  3. 30 分

我该怎么做?

这是我的代码:

var database = firebase.database();
var userRef = database.ref('countries');
userRef.orderByChild("points").once('value', function(snapshot) {
    var tr;
    var rank = 1;

    snapshot.forEach((countrySnapshot) => {
        tr = $('<tr/>');
        tr.append("<td>" + rank + "</td>");
        tr.append("<td>" + countrySnapshot.val().country.toLocaleString() + "</td>");
        tr.append("<td>" + countrySnapshot.val().points.toLocaleString() + "</td>");
        $('table').append(tr);
        rank = rank + 1;
});
})

现在是这样的:

picture

【问题讨论】:

    标签: javascript html firebase firebase-realtime-database


    【解决方案1】:

    在执行forEach 之前反转数组。看着documentation

    具有数值的子项紧随其后,按升序排列。如果 多个孩子对于指定的具有相同的数值 子节点,按key排序。

    var database = firebase.database();
    var userRef = database.ref('countries');
    userRef.orderByChild("points").once('value', function(snapshot) {
        var tr;
        var rank = 1;
        snapshot.reverse(); //add in this line
        snapshot.forEach((countrySnapshot) => {
            tr = $('<tr/>');
            tr.append("<td>" + rank + "</td>");
            tr.append("<td>" + countrySnapshot.val().country.toLocaleString() + "</td>");
            tr.append("<td>" + countrySnapshot.val().points.toLocaleString() + "</td>");
            $('table').append(tr);
            rank = rank + 1;
    });
    })
    

    【讨论】:

    • 当我使用代码“Uncaught TypeError: snapshot.reverse is not a function”时出现此错误
    • 你能得到快照的类型吗? console.log(typeof 快照);
    • 它返回了“对象”
    最近更新 更多