gpt4 book ai didi

javascript - 新手尝试让 localStorage 工作

转载 作者:行者123 更新时间:2023-11-27 23:05:46 26 4
gpt4 key购买 nike

我无法让下面的代码表达除未定义以外的任何内容。我什么地方做得不对?我也不确定分数函数是如何工作的。到目前为止,我只编写了普通的 function doSomething() {} 方法。谢谢。

var score = score || {};

score = {
saveHighScore: function(tally) {
var high_score = localStorage.high_score;
if (typeof high_score == 'number') {
if (tally > high_score) {
localStorage.high_score = tally;
}
} else {
localStorage.high_score = tally;
}
},
getHighScore: function() {
var high_score = localStorage.high_score;
if(typeof high_score !== 'number') {
high_score = 0;
localStorage.high_score = high_score;
}
return high_score;
}
}

window.console.log("Score: ", score.getHighScore());

最佳答案

您的问题是本地存储将值存储为字符串键/值对,因此您需要 parseInt:-

var score = score || {};

score = {
saveHighScore: function(tally) {
var high_score = localStorage.high_score;
if (typeof high_score == 'number') {
if (tally > high_score) {
localStorage.high_score = tally;
}
} else {
localStorage.high_score = tally;
}
},
getHighScore: function() {
var high_score = parseInt(localStorage.high_score);
if(typeof high_score !== 'number') {
high_score = 0;
localStorage.high_score = high_score;
}
return high_score;
}
}

score.saveHighScore(100)

window.console.log("Score: ", score.getHighScore());

I have no idea why, but I reloaded the same code posted above and it returns Score: 0 in the console.

它返回0的原因是在getHighScore内部,它从本地存储中检索值并比较它是否不是数字,如果不是数字您将其设置为0。由于本地存储将所有值保存为字符串,因此它始终将您的值设置为 0

I'm not sure how the score function works, either

这些只是对象内部的函数。

关于javascript - 新手尝试让 localStorage 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com