如何在JavaScript中持久化存储同属性对象数组至localStorage?
Hey there! I see exactly what's going on here—your data gets wiped on refresh because you're starting with an empty datas array every time the page loads. Let's fix that quickly.
The Root Cause
Right now, you have let datas = []; hardcoded. Every time the page refreshes, this line resets your array to empty. When you add new data, you're pushing to this empty array and overwriting the old data in localStorage instead of appending to it.
The Solution
We need to load existing data from localStorage when the page first loads, so your datas array starts with any previously saved entries. If there's no existing data yet, we'll default to an empty array.
Modified Code
Here's your updated code with the key fixes highlighted:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form id="regform"> <div id="name"> <h2 class="name">Name</h2> <input id="firstName" type="text" name="first" value=""><br> <label class="firstlabel" name="firstname">first name</label> <input id="lastName" type="text" name="last" value=""><br> <label class="lastlabel" name="lastname">last name</label> </div> <h2 class="name">Email</h2> <input id="email" type="text" name="email"> <h2 class="name">Password</h2> <input id="pass" type="password" name="password" autocomplete="off"> <h2 class="name">Phone</h2> <input id="code" type="text" name="area_code"> <label class="area-code">Area Code</label> <input id="number" type="text" name="phone"> <label class="phone-number">Phone Number</label> <button type="submit" id="btnreg" >Register</button> </form> <script> var fname=document.getElementById("firstName"); var lname=document.getElementById("lastName"); var btn=document.getElementById("btnreg"); var password=document.getElementById("pass"); var mail=document.getElementById("email"); var ariacode=document.getElementById("code"); var pnumber=document.getElementById("number"); // ✅ Load existing data from localStorage (or empty array if none exists) let datas = JSON.parse(localStorage.getItem("datas")) || []; var addData= (ev)=>{ ev.preventDefault(); var data = { name: fname.value +" "+ lname.value, passcode: password.value, email: mail.value, phonenumber: "+"+ariacode.value +" "+ pnumber.value }; datas.push(data); document.getElementById('regform').reset(); var data_serialized = JSON.stringify(datas); localStorage.setItem("datas", data_serialized); // Optional: Verify the data was saved var data_deserialized = JSON.parse(localStorage.getItem("datas")); console.log(data_deserialized); }; document.addEventListener('DOMContentLoaded', ()=>{ btn.onclick=addData; }); </script> </body> </html>
How This Works
JSON.parse(localStorage.getItem("datas")): Reads the saved data from localStorage and converts it back from a string to a JavaScript array.|| []: If localStorage doesn't have any "datas" entry (like on first use),localStorage.getItemreturnsnull, so we fall back to an empty array.- Now when you add new data, you're pushing it to an array that already contains your old entries, then saving the full updated array back to localStorage.
This way, even after refreshing the page, your existing data will load right back into the datas array, and new entries will be added on top of it instead of replacing everything.
内容的提问来源于stack exchange,提问作者Shanto Islam Dhrubo

