将对象保存在数组中以获取高分列表
Saving objects in array for highscore list
我正在用JQuery/Javascript做一个刽子手游戏,现在我想要一个高分表。我的想法是创建一个对象数组,但问题是当我尝试将游戏结果存储为数组中的对象(playername:playerscore pair)时,我的文本输出是"对象对象"而不是值。
var playerName;
var playerScore;
var gameResult = {};
var highscoreList = [];
function toHighscoreList() {
playerName = $('#nameTag').text(); // for example value "Henry"
playerScore = guessedWrong.length; // for example value 3
gameResult = {player: playerName, score: playerScore};
highscoreList[highscoreList.length] = gameResult;
$('#score1').text(highscoreList[0]);
};
我也尝试了这个版本,结果相同:
function toHighscoreList() {
playerName = $('#nameTag').text();
playerScore = guessedWrong.length;
gameResult = {player: playerName, score: playerScore};
localStorage.setItem('gameResult', JSON.stringify(gameResult));
$('#score1').text(JSON.parse(localStorage.getItem('gameResult')));
};
有没有另一种方法来存储多个键:值对?我仍然希望轻松修改高分列表,以便我可以使用 sort() 方法进行排名并用较高的分数替换较低的分数。
您可能希望对高分进行排序,因此请尝试:
var playerName;
var playerScore;
var gameResult = {};
var highscoreList = [];
function toHighscoreList() {
playerName = $('#nameTag').text(); // for example value "Henry"
playerScore = guessedWrong.length; // for example value 3
gameResult = {player: playerName, score: playerScore};
highscoreList.push(gameResult);
highscoreList.sort(function(a,b) { return (b.score - a.score ) });
$('#score1').text(highscoreList[0].player + " - score: "+ highscoreList[0].score);
};
使用 "highscoreList[0]",您可以获得存储在数组中的第一个对象。你应该注意获取单个值(如highscoreList[0].player或highscoreList[0].score),格式化并打印它。
$('#score1').text(highscoreList[0]);
可以替换为
$('#score1').text(highscoreList[0].player + ' has scored ' + highscoreList[0].score);
相关文章:
- 如何在jquery中获取列表项的最顶端父项的文本
- 根据列表元素的值使用JQuery获取列表元素
- 正在获取列表项位置()
- 如何在委托中获取列表项中元素的内部HTML
- 用javascript从mysql中获取列表变量
- 在 jQuery 的自动完成中获取列表项单击的名称
- Jquery - 如何获取列表项中的元素
- 在 django 中获取列表值
- 在 Vista Gadget 中使用 Javascript 获取列表数据
- 使用 SPServices 从另一个域上的 SharePoint 获取列表项总数
- jQuery:如何获取列表元素的索引
- 获取列表项中当前 ID 的值
- 获取列表项的值并发布到 ajax
- 获取列表中的第一个 DOM 元素
- 获取列表项的文本内容
- 如何在javascript中获取列表中td的值
- $ionicLoading在从Ionic中的Firebase获取列表期间未显示
- Iscroll-Jquery-获取列表项的位置
- 从自动填充的JSON列表中获取列表选项值,并传递给JS函数
- 如何获取列表项'JSON加载的未排序列表中的s id