You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面重载时给localStorage变量加1出现字符串拼接,代码错误原因是什么?

问题原因

localStorage 存储的所有内容都会自动转为字符串类型,你的代码触发了字符串拼接逻辑而非数值加法:

  1. 首次运行时localStorage.getItem('Counter')返回null,null + 1运算时会被隐式转为字符串'1'存入存储
  2. 后续重载取出的都是字符串格式的数字,字符串 + 1会执行拼接操作,因此出现1→11→111的结果
修正代码
// 取出值转为数字,兜底处理首次为空的情况
var Counter = Number(localStorage.getItem('Counter')) || 0;
// 数值加1后存入
localStorage.setItem('Counter', Counter + 1);
// 打印结果
console.log(localStorage.getItem('Counter'));
修正说明
  • 用Number()将取出的字符串转为数值类型,避免拼接逻辑
  • 加|| 0做兜底,避免首次取值为null时转成NaN的异常情况
  • 运算后的数值存入localStorage时会自动转成字符串,不影响下次取出后再次转为数值运算

内容的提问来源于stack exchange,提问作者Pepe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:09:04