的最高得分的排序阵列
在为我的学校项目编码基本游戏时,我会遇到一个问题,试图存储和排序 highScore 数组,我相信使用>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"));
}
}
您可以添加所有播放器作为
之类的对象数组
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);
"分类玩家"将包含在TOP