问题
Trying to simply store a variable using localStorage, retrieve it later on as an integer, add it to another integer and then store it again. However, it seems to be treating the integer as a string and concatenates numbers instead. I have tried using JSON.stringify and parse but it doesn't work and I can't see why. (the variable hours
is definitely an integer.)
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));
}
I'm sure I'm missing something really obvious so if someone could point it out to me that would be fantastic, thanks!
回答1:
localStorage treats everything as a string. You have to parseInt its value before using it as an Integer.
Besides, you should use the JSON Stringify to convert array to strings. Your variable hours is an Int so you don't need the Stringify it.
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);
}
来源:https://stackoverflow.com/questions/21217702/localstorage-concatenating-integer-instead-of-adding