Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - localStorage concatenating Integer instead of adding

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...