使用getItem()和setItem()后LocalStorage出现异常结果的问询
杂货待办清单LocalStorage添加项的控制台输出异常问题
我正在开发一个简易杂货待办清单,支持添加、删除和更新项,将数据以对象数组的形式存储在LocalStorage的list键下。
我编写了addToLocalStorage()函数用于获取初始列表并添加新项,但出现了异常:添加单个项后,console.log输出的原有列表竟包含了后续添加的项。
函数代码如下:
function addToLocalStorage(id, value) { const groc = {id, value}; let items = localStorage.getItem('list')?JSON.parse(localStorage.getItem('list')):[]; console.log("Previous items", items); items.push(groc); console.log("Pushing ", groc); localStorage.setItem('list',JSON.stringify(items)); console.log("Right Now the list is ", items); }
其中id由当前毫秒数生成。
添加第一个项Eggs时,输出符合预期:
Adding to the list Previous items [] Pushing {id: '1685891620219', value: 'Eggs'} Right Now the list is [{…}] 0: {id: '1685891620219', value: 'Eggs'} length: 1 [[Prototype]]: Array(0)
但添加第二个项Milk时,Previous items显示已经包含第二个新项的列表,不符合预期(预期应该只显示第一个项):
Adding to the list Previous items [{…}] [{…}] 0: {id: '1685891620219', value: 'Eggs'} 1: {id: '1685891909713', value: 'Milk'} length: 2 [[Prototype]]: Array(0) Pushing {id: '1685891909713', value: 'Milk'} Right Now the list is (2) [{…}, {…}] 0: {id: '1685891620219', value: 'Eggs'} 1: {id: '1685891909713', value: 'Milk'} length: 2[[Prototype]]: Array(0)
问题原因分析
这不是你的代码逻辑错误,而是浏览器控制台的惰性求值特性导致的视觉误导:
- 当你用
console.log("Previous items", items)输出数组时,浏览器并没有立即生成数组的当前状态快照,而是只保存了一个指向该数组的引用。 - 之后你执行
items.push(groc)修改了数组内容,当你在控制台展开数组查看详情时,浏览器才会去读取数组的最新状态——也就是已经添加新项后的状态。 - 所以你看到的
Previous items展开后的内容,其实是数组被修改后的状态,而非执行console.log那一刻的真实状态。
如果想验证执行console.log时的真实状态,可以把数组转换成字符串打印,这样会输出当时的快照:
console.log("Previous items", JSON.stringify(items));
内容的提问来源于stack exchange,提问作者Satyam Rai
相关产品推荐
相关产品推荐

