localStorage写入400条数据后仅读取23条,请求排查问题
Let's break down why your read loop is only showing 23 logs instead of 400—this is a common gotcha with browser dev tools and scoping, so let's fix it step by step:
1. Browser Console is Collapsing Duplicate Logs
This is the most likely culprit. Since you're storing the exact same value ('empty') for every key, modern browser dev tools automatically merge identical consecutive log entries to keep the console clean. Instead of showing 400 identical lines, it'll display something like empty (23 times) (the number might vary based on how the console batches updates).
How to Verify:
Modify your write script to store unique values so each log entry is distinct:
for(let i=1;i<401;i++){ localStorage.setItem(i,'empty_' + i); }
Then run your read loop again—you should see all 400 entries printed individually.
2. Implicit Global Variable Scope is Causing Interference
If you didn't declare i with let or const in your loops, you're using an implicit global variable. This means other scripts or browser extensions could accidentally overwrite the value of i mid-loop, causing it to exit early.
Fix:
Use block-scoped variables for your loop counter to isolate it:
// Write script with let for(let i=1;i<401;i++){ localStorage.setItem(i,'empty'); } // Read script with let for(let i=1;i<401;i++){ console.log(localStorage.getItem(i)); }
This ensures each iteration's i is independent and can't be modified from outside the loop.
3. Quick Check to Confirm Storage Worked
Before assuming the read loop is broken, verify that all 400 items are actually stored in localStorage. Run this in your console:
console.log(localStorage.length); // Should return 400 if storage succeeded
If this returns 400, the issue is definitely with how the console displays logs, not with localStorage itself.
内容的提问来源于stack exchange,提问作者Manuxx

