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

无法将person对象push到localStorage存储的数组,报Cannot read properties of null错误

报错根因

  • 核心触发点:newarray为null,你尝试调用null的push方法才抛出该错误,导致newarray为null的原因有两个:
    1. localStorage.getItem()的参数必须是字符串类型的存储key,你错误传入了数组变量userArray,自然取不到正确的存储值
    2. 首次加载页面时localStorage里还没有存储对应的用户数组,getItem默认返回null,JSON.parse(null)结果还是null
  • 其他关联逻辑错误:
    1. 全局定义person时就直接读取input值,此时用户还没有输入内容,拿到的永远是空值
    2. 调用storeName()时没有传入参数,函数内定义的形参person、userArray都是undefined,逻辑完全混乱
    3. 邮箱重复判断逻辑错误,你只读取了localStorage.email这个单独字段,没有遍历存储的用户数组校验邮箱是否重复

修复方案

首先调整逻辑:存储用户数组固定使用userList作为localStorage的key,点击注册按钮时再读取表单值、先判断localStorage里有没有已有的用户数组,没有就初始化空数组,再校验邮箱、追加新用户后重新存储。
修正后的完整代码如下:

<p class="center" >
    name:<br> <input type="text" id="nameinput" required><br>
    email:<br><input type="email" id="emailinput" required><br>
    password:<br><input type="password" id="passwordinput" required><br>
    <button id="registerbutton" onclick="containsObject()">Register<button>
</p><br><p id="feedback"></p><br>
<button onclick="clearStorage()">Clear Storage</button>

<script>
const feedback = document.getElementById("feedback");
// 固定存储key,避免拼写错误
const STORAGE_KEY = "userList";

function containsObject() {
    // 点击注册时再读取表单值
    const name = document.getElementById("nameinput").value.trim();
    const email = document.getElementById("emailinput").value.trim();
    const password = document.getElementById("passwordinput").value.trim();
    if(!name || !email || !password) {
        feedback.innerHTML = "请填写完整信息";
        return;
    }
    const person = {name, email, password};
    // 读取已有的用户列表,没有就初始化空数组
    let userArray = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
    // 校验邮箱是否重复
    const isEmailExist = userArray.some(item => item.email === email);
    if(isEmailExist) {
        feedback.innerHTML = "email exist";
        return;
    }
    // 追加新用户并存储
    userArray.push(person);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(userArray));
    feedback.innerHTML = "注册成功";
    console.log(userArray);
}

function clearStorage() {
    localStorage.removeItem(STORAGE_KEY);
    feedback.innerHTML = "存储已清空";
}
</script>

关键修改点

  • 固定使用字符串userList作为localStorage的存储key,存取都用同一个key
  • 读取本地存储时加了兜底逻辑JSON.parse(...) || [],如果取不到值就默认赋值为空数组,永远不会出现null调用push的情况
  • 把表单读取逻辑放到点击注册按钮之后,确保拿到的是用户输入的最新值
  • 优化了邮箱重复校验逻辑,遍历已存储的用户数组判断重复,符合业务需求
  • 简化了冗余函数,逻辑更清晰

内容的提问来源于stack exchange,提问作者Mo7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:24:06