You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中持久化存储同属性对象数组至localStorage?

Fix: Preserve localStorage Data After Page Refresh

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.getItem returns null, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:17:57