[英]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.