【发布时间】:2014-01-19 22:21:14
【问题描述】:
尝试使用 localStorage 简单地存储变量,稍后将其作为整数检索,将其添加到另一个整数,然后再次存储。但是,它似乎将整数视为字符串并连接数字。我尝试过使用 JSON.stringify 和解析,但它不起作用,我不明白为什么。 (变量hours绝对是整数。)
if (localStorage.getItem('hours_worked') === null) {
localStorage.setItem('hours_worked', JSON.stringify(hours));
}
else {
var temp_hours = JSON.parse(localStorage.getItem('hours_worked'));
var temp_hours1 = temp_hours + hours;
alert(temp_hours1);
localStorage.setItem('hours_worked', JSON.stringify(temp_hours1));
}
我确定我遗漏了一些非常明显的东西,所以如果有人可以向我指出,那就太好了,谢谢!
【问题讨论】:
-
你的 JSON 是什么样子的?好像你有一个字符串而不是一个数字。致电
parseInt(..., 10)或Number(...)。更好? -
谢谢,是的,我曾经玩过 parseInt,但之前无法让它工作,感谢您为我指明了正确的方向,现在一切都解决了!