Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...