localStorage串联整数而不是添加 [英] localStorage concatenating Integer instead of adding

查看:105
本文介绍了localStorage串联整数而不是添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试简单地使用localStorage存储变量,稍后将其作为整数检索,将其添加到另一个整数,然后再次存储.但是,似乎将整数视为字符串,而是连接数字.我尝试使用JSON.stringify和解析,但是它不起作用,我也看不出为什么. (变量hours绝对是整数.)

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!

推荐答案

localStorage将所有内容都视为字符串.在将其用作整数之前,您必须先解析其值.

localStorage treats everything as a string. You have to parseInt its value before using it as an Integer.

此外,您应该使用JSON Stringify将数组转换为字符串.您的可变小时数是整数,因此您不需要将其字符串化.

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

这篇关于localStorage串联整数而不是添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆