开发三页面健身应用时,在for in循环中使用localStorage的问题
Hey there! Welcome to StackOverflow—glad you finally took the plunge and joined to ask your question directly. It’s way easier to get targeted help when you’re stuck on a specific issue, so great call reaching out! 😊
localStorage Issues in Your for...in Loop Since you’re building a 3-page fitness app (love the concept, by the way!), let’s break down the most common pitfalls with for...in and localStorage that might be tripping you up, along with fixes tailored to your use case:
Avoid inherited prototype properties: The
for...inloop doesn’t just iterate over your stored items—it also picks up built-inlocalStorageproperties likelengthorkey(). This can cause unexpected behavior in your loop. Fix this by adding ahasOwnProperty()check to ensure you’re only working with your own keys:for (let key in localStorage) { // Only process keys you've added to localStorage if (localStorage.hasOwnProperty(key)) { const storedData = localStorage.getItem(key); // Your logic to filter workouts by equipment/difficulty here } }Don’t forget JSON serialization:
localStorageonly stores strings, so if you’re saving workout objects (with equipment type, difficulty, exercises, etc.), you need to convert them to strings when storing, and parse them back when retrieving. Skipping this will lead to messy, unreadable data in your loop:// Example: Storing a workout object const sampleWorkout = { equipment: 'bike', difficulty: 'beginner', exercises: ['Warm-up pedal', 'Interval sprints'] }; localStorage.setItem('bike-beginner-1', JSON.stringify(sampleWorkout)); // Retrieving in your loop for (let key in localStorage) { if (localStorage.hasOwnProperty(key)) { // Parse the string back into an object const workout = JSON.parse(localStorage.getItem(key)); // Now you can check workout.equipment or workout.difficulty } }Filter keys to match user selection: Since page 2 needs to show workouts matching the user’s chosen equipment and difficulty, you can add checks right in the loop to skip irrelevant items. This saves you from processing every stored item unnecessarily:
// Assume these are the user's selections from page 1 const userEquipment = 'rower'; const userDifficulty = 'advanced'; for (let key in localStorage) { if (localStorage.hasOwnProperty(key)) { const workout = JSON.parse(localStorage.getItem(key)); // Only keep workouts that match the user's choices if (workout.equipment === userEquipment && workout.difficulty === userDifficulty) { // Add this workout to your page 2 display list console.log('Matching workout:', workout); } } }Try an alternative loop method: If
for...infeels too error-prone, use a standardforloop withlocalStorage.lengthandlocalStorage.key(index). This method only iterates over your stored keys, so you don’t have to worry about prototype properties:for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); const workout = JSON.parse(localStorage.getItem(key)); // Process the workout as needed }
If none of these fix your issue, sharing a snippet of your current loop code would help zero in on the exact problem—but these are the most common fixes for the scenario you described. Good luck with your app, can’t wait to hear how it turns out!
内容的提问来源于stack exchange,提问作者Rezaa91

