在为我的学校项目编写基本游戏时,我遇到了一个问题,试图存储和排序高分数组,我相信使用 localstorage 是正确的方式去,但由于数组本身由一个名称和一个分数组成,我在尝试排序时遇到了问题。
https://jsbin.com/fagupohozo/1/edit?js
allPlayers = {};
function showScore(){
getStoragePlayer();
addPlayer();
setStoragePlayer();
}
function addPlayer(){ //Adds a player to the array with score and name
allPlayers[prompt("What's your name")] = score;
}
function setStoragePlayer(){ // Sends the array to the cloud for saving
localStorage.setItem("PlayerArray", JSON.stringify(allPlayers));
}
function getStoragePlayer() { // Downloads the array from the cloud
if (localStorage.PlayerArray != null) {
allPlayers = JSON.parse(localStorage.getItem("PlayerArray"));
}
}
答案 0 :(得分:0)
您可以将allPlayers添加为对象数组,例如
allPlayers = [
{name:"John", score:20},
{name:"Smith", score:40}
]

然后用分数对其进行排序,这样你就可以得到高分以及排序数组中该玩家的名字
var allPlayers = [
{name:"John", score:20},
{name:"Smith", score:40}
];
var sortedPlayers = allPlayers.sort(function(a, b){
return b.score - a.score
});
console.log(sortedPlayers);

" sortedPlayers"将包含排名最高的排序数组