我尝试创建一些功能,可以按最高分值对Firebase中的数据进行排序,只显示前5名。现在我可以轻松地在网上显示所有数据,这对我来说并不是很有用。
功能gotData
为我提供Firebase中正确的数据格式,并将每个分数放在列表中的li元素中。
console.log(JSON.stringify(scores)) print
{"-KYxmoU7NnbTk0EpURZO":{"initials":"Rafi","score":8},
"-KYxnLZ0HyftwOENmTs1":{"initials":"Wichru","score":13},
"-KYxndQcCmiRDet-kLlK":{"initials":"Meg","score":36},
"-KYxpnFkihQhung3_1s_":{"initials":"asas","score":0},
"-KZ0I4eeAvReZdlw-9dL":{"initials":"Ryan","score":28}}
我也做了:
var values = Object.values(scores);
values.sort( (a, b) => b.score - a.score );
和对象按分数值排序,但我仍无法在网页视图中打印
firebase.initializeApp(config);
database = firebase.database();
var ref = database.ref('scores');
console.log(ref);
ref.on('value', gotData, errData);
function gotData(data) {
var scorelistings = document.querySelectorAll('.scorelisting');
for (var i = 0; i < scorelistings.length; i++){
scorelistings[i].remove();
}
var scores = data.val();
var keys = Object.keys(scores);
var olList = document.getElementById('list');
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var initials = scores[k].initials;
var score = scores[k].score;
var li = document.createElement('li');
li.classList.add('scorelisting');
$(olList).append(li);
var scoreArr = $('ol').find('li');
var count = $("ol").find("li").length;
li.innerText = initials + ": " + score;
}
}
function errData(err) {
console.log('error');
}
function submitScore(e) {
var data = {
initials: nickname.value,
score: score
}
e.preventDefault();
// console.log(data);
ref.push(data);
scoreBoard.style.display = "none";
highscoreBoard.style.display = "block";
}
答案 0 :(得分:0)
您可以通过基于得分对象创建新数组来对数据进行排序,该对象包含得分中的对象。因此键被顺序(数组)索引替换(键被添加到每个对象的副本中,因此您仍然拥有它)。然后排序该数组很简单。并且,一旦有5个结果,就可以使用.every()
停止迭代:
var scores = data.val();
Object.keys(data.val())
.map ( key => Object.assign({ key }, scores[key]) )
.sort( (a, b) => b.score - a.score )
.every( (score, rank) => {
var li = document.createElement('li');
li.classList.add('scorelisting');
li.textContent = score.initials + ": " + score.score;
$(olList).append(li);
return rank < 4;
});