[英]Why does my localStorage variable break on a page refresh?
我的西蒙游戏代码还有另一个问题。 我添加了一个 localStorage 变量来保存页面加载之间的高分。 显然,高分只会随着你的分数超过它而增加,然后 localStorage 变量应该捕获那个新分数。 在重新加载我的 localStorage 变量时,只需将数字 1 添加到高分的末尾。 因此,假设您设置了 16 的高分,并且您关闭页面到 go 做其他事情,然后当您回来玩更多时,您的 16 的高分出现在页面加载中。 您单击“开始”开始游戏,当您输入 select 时,您的高分正确输入为 161 和 1611 等。
以下是所有相关代码:
var score = 0;
var level = 0;
//Call high score from localStorage or display the same int as score
var highScore = localStorage.getItem("highScore") || score;
$("#score").html(`${score}`); //Display score on webpage
$("#level").html(`${level}`); //Display level on webpage
$("#high-score").html(`${highScore}`); //Display high score on webpage
//Game logic
$("#start-button").on("click", function() {
var buttons = document.getElementsByClassName("js-button");
var buttonsToClick = chooseRandomButtons(buttons);
currentButtons = buttonsToClick;
flashButtons(buttonsToClick, 0);
//Every time the start button is pressed, increment level count by 1
level += 1;
$("#level").html(`${level}`);
var currentOrder = 0;
$(".js-button").off("click").on("click", function() {
var selectedButton = $(this)[0];
var button = currentButtons[0];
//Check input matches array
if (selectedButton === button) {
currentButtons.splice(button,1);
//When a correct input is recorded, increment score & high score by 1
score += 1;
highScore += 1;
$("#score").html(`${score}`);
$("#high-score").html(`${highScore}`);
//Display win message if you reach the end of the array
if (score == 111 || score == 100 || score == 98 || score == 88 || score == 78
|| score == 69 || score == 60 || score == 52 || score == 44 || score == 37
|| score == 30 || score == 24 || score == 18 || score == 13 || score == 8
|| score == 4) {
alert("Well done! Click start to begin the next level");
}
//Display restart message if input does not match array
} else {
currentButtons = buttonsToClick;
alert("Sorry, that was wrong. Click 'Start' to try again");
score = 0;
level = 0;
$("#score").html(`${score}`);
$("#level").html(`${level}`);
localStorage.setItem("highScore", highScore); //Set persistent high score through page loads
}
});
})
localStorage 存储字符串。 您正在获得隐式转换。 基本上score + (1).toString()
在设置值之前,您应该检查分数是否高于高分。 我省略了数字转换,因为有隐式转换,所以不需要。 但我建议您无论如何添加它,以避免出现问题。
替换highScore += 1;
和
if (score > highScore)
highScore = score;
下面实际上不需要修复您的代码,但无论如何您都应该这样做:
var highScore = parseInt(localStorage.getItem("highScore")) || score;
您的本地存储是字符串。
改变:
var highScore = localStorage.getItem("highScore") || score;
至:
var highScore = +localStorage.getItem("highScore") || score;
localStorage 的类型是 String 你必须将 localStorage 转换为 Number 类型,如下代码:
Number(localStorage.getItem("highScore"))
有关 localStorage 的更多信息,请阅读此文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.