-
Notifications
You must be signed in to change notification settings - Fork 2
/
highscore.js
45 lines (30 loc) · 1.1 KB
/
highscore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var currentUser = JSON.parse(localStorage.getItem( "currentScore" ));
// console.log(currentUser.playerName)
// console.log(currentUser.playerScore)
// document.getElementById("display-current-score").innerHTML = "Name: " + currentUser.playerName + " " + currentUser.playerScore;
//ADD ON
var highScoreList = $("#highScores");
//creates the ol list elements to display them
function loadHighScores(){
let currentScores = JSON.parse(localStorage.getItem("highScores"));
if (currentScores !== null) {
sortByKeyDesc(currentScores,"playerScore");
currentScores.forEach(element => {
var newLi = $("<li>")
.text(element.playerName+": "+element.playerScore);
highScoreList.append(newLi);
});
}else{
highScoreList.empty();
}
}
//sorts an array of objects by the selected key (descending);
function sortByKeyDesc(array, key) {
return array.sort(function(a, b) {
let x = a[key];
let y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
loadHighScores();
localStorage.removeItem("highScores");