我正在尝试创建一个 javascript/HTML 游戏,其中可以在多次访问该网站时保存积分,并且保存功能工作得很好,但是当我将其转换为加载时的积分变量时页上,+= 运算符将不起作用。它不会使用加法来更新变量,而是将数字添加到变量值的末尾。例如,如果您说 100 += 1,那么输出为 101 才有意义,但实际上却是 1001。
我发现它实际上是本地存储。如果只是将我尝试显示的分数设置为 0 而不是过去获得的分数,则效果很好。可能会发生此错误,因为我正在使用带有 repl.it 的免费网络托管,因此我与许多其他网站共享域。我想过测试它是否可以更好地使用 cookie,但我从未使用过 cookie,所以我想在尝试学习它们之前先检查这里。
var points = 0;
points += localStorage.points;
// The below is tied to a save button
function saveData() {
localStorage.points = points;
}
/*This is also tied to a button with an amount of one, and this is
where errors occur. */
function addPoints(amount) {
points += amount;
}
抱歉,如果我的内容有些草率,我对 JavaScript 和游戏开发都很陌生。另外,事实上,我确实有一个检查器来查看本地存储是否可用。
最佳答案
localStorage
始终将值存储为字符串。摘自mozilla :
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
您需要首先将点
转换为数字。
var points = 0;
points += +localStorage.points; // + casts it to a number
关于javascript - 有谁知道为什么会出现数学和本地存储的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364870/