localStorage concatenating Integer instead of adding

亡梦爱人 提交于 2019-12-20 06:39:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!