Web 浏览器本地存储返回值为 null,但在 JavaScript 中未显示为 null 值

web browser local storage return value is null but it's not shown as a null value in JavaScript

提问人:Dasun wijesundara 提问时间:6/17/2023 最后编辑:Dasun wijesundara 更新时间:6/17/2023 访问量:285

问:

enter image description here

这是我的本地存储键值对

ProductsInCart : 空

当我在 JavaScript 中以流畅的行访问它时,

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

cartItemsList 值为 null,

但是当我用以下条件检查它时,

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

输出不为空,

这是我的原始JavaScript代码,

 var imgSrc = JSON.parse(sessionStorage.getItem('storedSingleProductImage'))
        MainImg.src = imgSrc;

        var sProductCategory = document.querySelector('#productCategory')
        var sProductName = document.querySelector('#productName')
        var sProductPrice = document.querySelector('#productPrice')
        var sNumberOfproducts = document.querySelector('#numberOfproducts');

        let sProdCategory = JSON.parse(sessionStorage.getItem('storedSingleProductCategory'))
        let sProdName = JSON.parse(sessionStorage.getItem('storedSingleProductName'))
        let sProdPrice = JSON.parse(sessionStorage.getItem('storedSingleItemPrice'))

        sProductCategory.innerHTML = sProdCategory
        sProductName.innerHTML = sProdName
        sProductPrice.innerHTML = sProdPrice
        let sNumberOfprod =1;
        sNumberOfproducts.addEventListener('input', () => {
             sNumberOfprod = sNumberOfproducts.value;
        });
        function addToCart() {

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

            let cartItems = [];
            //this condition true for null values also
            if(cartItemsList !== null){

                //I want parse a not null value for the JSON.parse() because it will pop a error otherwise
                 cartItems =  JSON.parse(cartItemsList);
            }
  
            cartItems.push(
                {
                    sProdCategory,
                    sProdName,
                    sProdPrice,
                    sNumberOfprod,
                    imgSrc
                }
            )
            localStorage.setItem("ProductsInCart", JSON.stringify(cartItems));
            alert(`${sNumberOfprod} items of ${sProdName}-(${sProdCategory}) added to the cart.`)
        }

这是代码的输出

Uncaught TypeError: Cannot read properties of null (reading 'push')
    at addToCart (sproduct.html:154:23)
    at HTMLButtonElement.onclick (sproduct.html:54:58)
javascript 数组 json null 本地存储

评论

1赞 epascarello 6/17/2023
就我个人而言,我会这样做const cartItems = JSON.parse(localStorage.getItem("ProductsInCart")) || [];

答:

-1赞 Amit Poudyal 6/17/2023 #1

您应该首先设置项目,并应在 Web 浏览器的控制台中检查 localstorage。

localstorage.setItem("ProductsInCart");
console.log("localstorage");

评论

0赞 epascarello 6/17/2023
你为什么要这样做?
0赞 Sudhir kumar 6/17/2023 #2

您之前没有解析过 JSON 对象 if 条件 在从 localStorge 获取数据时使用 JSON.parse

let cartItemsList = JSON.parse(localStorage.getItem("ProductsInCart"));
let cartItems = [];
 //this condition true for null values also
if(cartItemsList !== null){
//I want parse a not null value for the JSON.parse() because it will pop a error otherwise
 cartItems =  JSON.parse(cartItemsList);
}
0赞 Predator13 6/17/2023 #3

在本地存储中,所有值都存储为 String,因此当您获取 item 时,它会返回:-

cartItemsList = "null" and not cartItemsList = null

因此,在像这样检查之前,要么从字符串“null”中删除双引号:-

 cartItemsList = cartItemsList.replace(/['"]+/g, '')

或者你把你的条件检查为“null”,比如:-

if (cartItemsList != "null")
2赞 Siva K V 6/17/2023 #4

localStorage.setItem将值保存为非字符串值。您需要检查“null”或之后的值。stringifiedJSON.parse

建议在使用 localStore 时始终使用以下包装器实用程序

const getLocalStorageValue = (key, defaultValue = undefined) => {
  const strValue = localStorage.getItem(key);
  let value = defaultValue;
  if (strValue) {
    try {
      value = JSON.parse(strValue);
    } catch ({ message }) {
      // execption
      console.info("Caught error while JSON parse", message);
    }
  }
  return value;
};

const setLocalStorageValue = (key, value) => {
  try {
    const valueStr = JSON.stringify(value);
    localStorage.setItem(key, valueStr);
  } catch ({ message }) {
    // execption
    console.info("Caught error while JSON stringify", message);
  }
};