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

LocalStorage取值显示null但JS判断异常,push触发TypeError求助

问题分析与解决方案

问题场景

本地存储中ProductsInCart的键值对为:ProductsInCart : null
执行以下代码获取值时,控制台打印null:

let cartItemsList = localStorage.getItem("ProductsInCart");
console.log(cartItemsList)

但执行条件判断时,输出not null:

if (cartItemsList != null) {
    console.log('not null')
} else {
    console.log('null')
}

最终执行完整代码时,出现报错:

Uncaught TypeError: Cannot read properties of null (reading 'push')
    at addToCart (sproduct.html:154:23)
    at HTMLButtonElement.onclick (sproduct.html:54:58)

问题原因

  1. LocalStorage存储限制:LocalStorage仅支持存储字符串类型数据。你看到的ProductsInCart : null实际是存储了字符串"null",而非JavaScript原生的null值。
  2. 判断逻辑失效:localStorage.getItem获取到的是字符串"null",此时"null" != null结果为true(字符串与null属于不同类型),导致条件判断进入not null分支。
  3. push报错根源:进入分支后执行JSON.parse("null")会得到原生null值,cartItems被赋值为null,而null不是数组,调用push方法触发类型错误。

解决方案

1. 修正判断逻辑,覆盖字符串"null"场景

判断时同时检查获取值是否为null或字符串"null",仅对有效数组字符串进行解析:

2. 确保cartItems始终为数组类型

初始化后通过额外校验,保证cartItems在任何情况下都是数组,避免后续push报错。

修改后的addToCart函数

function addToCart() {
    let cartItemsList = localStorage.getItem("ProductsInCart");
    console.log(cartItemsList);

    let cartItems = [];
    // 同时排除null和字符串"null"的情况
    if (cartItemsList !== null && cartItemsList !== "null") {
        try {
            cartItems = JSON.parse(cartItemsList);
            // 额外校验解析结果是否为数组,防止存储非数组数据
            if (!Array.isArray(cartItems)) {
                cartItems = [];
            }
        } catch (e) {
            console.error("解析购物车数据失败:", e);
            cartItems = [];
        }
    }

    cartItems.push({
        sProdCategory,
        sProdName,
        sProdPrice,
        sNumberOfprod,
        imgSrc
    });
    localStorage.setItem("ProductsInCart", JSON.stringify(cartItems));
    alert(`${sNumberOfprod} items of ${sProdName}-(${sProdCategory}) added to the cart.`)
}

3. 优化初始存储逻辑(可选)

页面加载时初始化本地存储,直接存入空数组的字符串形式,从根源避免"null"的存储问题:

// 页面加载时执行,初始化购物车存储
if (!localStorage.getItem("ProductsInCart")) {
    localStorage.setItem("ProductsInCart", JSON.stringify([]));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:27:42