About Leader Board in Javascript (Array) Help Me Please
I need help with a score table for my game.
-1- I have 4 variables:
var Player1Score= 44;
var Player2Score= 12;
var Player3Score= 45;
var Player4Score= 26;
--2-- i make a Array:
var MyArray=[Player1Score,Player2Score,Player3Score,Player4Score];
--3-- sort the array:
MyArray.Sort();
--4-- Print:
----------HIGHSCORES----------
45
44
26
12
MY QUESTION IS: HOW I CAN PRINT THE NAME OF THE PLAYERS IN ORDER¿?
LIKE THIS:
----------HIGHSCORES----------
PLAYER 3 45
PLAYER 1 44
PLAYER 4 开发者_如何学编程 26
PLAYER 2 12
THANKS IN ADVANCE. GREETINGS
Store you score data like this:
scores = [
{ name: "John", score: 123 },
{ name: "Joe", score: 234 }
]
If you don't have names, then use any other properties like the player index.
Then sort the data with a custom sort function:
scores.sort(compareScores);
And provide the custom sort function:
function compareScores(a, b)
{
return a.score - b.score;
}
You may need to swap a and b in this function if you want a different order.
Print it like this:
for (i = 0; i < scores.length; i++)
{
name = scores[i].name;
score = scores[i].score;
... do something with name and score ...
}
var score_map = {score1 : player1, score2 : player2, score3 : player3,
score4 : player4};
var score_array = [score1,score2,score3,score4].sort();
for (var score in score_array) {
your_output_function(score_map[score]+" - "+score);
}
Associate the scores with the player names and store the association as a javascript object. Get your hands on the scores and sort them and then iterate through the keys and use the object that had the score/player associations to print out the players and their scores.
精彩评论