尝试简单地使用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));
}
我确定我确实缺少一些明显的东西,所以如果有人可以向我指出,那太好了,谢谢!
最佳答案
localStorage将所有内容都视为字符串。您必须先解析其值,然后才能将其用作整数。
此外,您应该使用JSON Stringify将数组转换为字符串。您的可变小时数是Int,因此您不需要Stringify。
if (localStorage.getItem('hours_worked') === null) {
localStorage.setItem('hours_worked', hours);
}
else {
var temp_hours = parseInt(localStorage.getItem('hours_worked'),10);
var temp_hours1 = temp_hours + hours;
alert(temp_hours1);
localStorage.setItem('hours_worked', temp_hours1);
}
关于javascript - localStorage串联整数而不是添加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21217702/