localStorage读取后数组length始终返回1的技术问题求助
问题排查与修复方案
我来帮你搞定这个问题~核心原因是页面刷新时,你把从 localStorage 取出的数组直接作为单个元素 push 到了新的 history 数组里,导致 history 变成了嵌套数组,所以history.length永远返回1(因为最外层数组始终只有一个元素——就是之前存储的整个数组)。
具体问题分析
举个实际流程的例子:
- 第一次点击菜单项,
history变成[0],存入 localStorage 的是"[0]"。 - 刷新页面,你取出
times = [0],然后执行history.push(times),此时history变成[[0]](外层数组只有1个元素,就是内层的[0]),所以history.length返回1。 - 再点击另一个菜单项,
history.push(1),此时history变成[[0], 1],存入 localStorage 的就是"[[0],1]",这就是你在开发者工具里看到的格式。
修复代码
把“将取出的数据添加到数组”的逻辑改成合并数组元素,而不是把整个数组作为单个元素push。修改后的jQuery代码如下:
jQuery(document).ready(function( $ ) { "use strict"; var history = [ ]; // 页面刷新后从localStorage获取数据 var retrievedData = localStorage.getItem('history'); var times = JSON.parse(retrievedData); // 若有数据则合并到数组(而不是push整个数组) if (times !== null) { // 方案1:使用concat合并数组(兼容所有浏览器) history = history.concat(times); // 方案2:使用扩展运算符(ES6+,现代浏览器支持,写法更简洁) // history.push(...times); } alert(history.length); // 现在会正确返回记录条数 // 点击事件:获取菜单项索引并添加到数组,存入localStorage var pushed = $('.active li'); pushed.click (function() { var index = pushed.index( this ); history.push(index); localStorage.setItem("history", JSON.stringify(history)); }); });
关键修改点说明
- 把
history.push(times)替换成history = history.concat(times):concat方法会把times数组的所有元素逐一合并到history里,而不是把times作为单个元素添加进去。 - 如果你只需要兼容现代浏览器,也可以用ES6的扩展运算符
history.push(...times),效果和concat完全一致,代码更简洁。
验证效果
修改后流程:
- 第一次点击菜单项,localStorage 存储
[0],history.length返回1。 - 刷新页面,
history会变成[0],history.length仍为1。 - 再点击另一个菜单项,
history变成[0,1],history.length返回2,localStorage 存储[0,1],完全符合预期。
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

