我正在尝试创建一个javascript / HTML游戏,该游戏可以通过多次访问站点来保存积分,并且save功能运行得很好,但是当我在加载网站时将其转换为points变量时,页面上,+ =运算符将不起作用。与其使用加法来更新变量,不如将数字添加到变量值的末尾。例如,如果您说100 + = 1,那么输出应该是101,而取而代之的是1001。
我发现它实际上是本地存储。如果只是将要显示的点设置为0,而不是过去的分数,则可以正常工作。可能发生此错误,因为我在repl.it上使用免费的虚拟主机,因此我与许多其他站点共享一个域。我考虑过测试它是否可以更好地与Cookie配合使用,但是我从未使用过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和游戏开发都是新手。另外,事实上,我确实有一个检查器,以查看本地存储是否可用。
答案 0 :(得分:3)
localStorage
始终将值存储为字符串。摘录自mozilla:
键和值始终是字符串(请注意,与对象一样,整数键将自动转换为字符串)。
您需要先将points
强制转换为数字。
var points = 0;
points += +localStorage.points; // + casts it to a number
答案 1 :(得分:2)
localStorage中存储的所有数据都是string
(或undefined
)。
因此,+=
运算符将执行字符串连接,而不是进行加法运算。
尝试以下操作:points += +localStorage.points
或points += Number(localStorage.points)
还必须确保初始值不是undefined
。
完整的解决方案是:
var points = 0;
if (localStorage.getItem('points') !== null) {
// ^^ Similar to localStorage.points !== undefined
points += +localStorage.points; // Now points won't be type-casted to string
}
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;
}
要了解为什么会发生这种情况,请运行以下示例:
const p = 0;
const s = '1';
const n = 1;
console.log(`p + s = ${p + s}, ${typeof(p+s)} | p + n = ${p + n}, ${typeof(p+n)} | p + +s = ${p + +s}, ${typeof(p + +s)}`);