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

0ejtzxu1  于 2023-06-25  发布在  Java
关注(0)|答案(4)|浏览(101)

下面是我的本地存储键值对
产品中心:零
当我在JavaScript中以流水线访问它时,

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

cartItemsList值为空,
但当我用下面的条件检查它时,

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)
wgx48brx

wgx48brx1#

localStorage.setItem将非字符串值保存为stringified。您需要检查“null”或JSON.parse之后的值。
建议在使用localStore时始终使用以下 Package 器实用程序

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);
  }
};
lpwwtiir

lpwwtiir2#

如果条件Use JSON.parse while get data from localStorge之前,您没有解析过JSON对象。

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);
}
goqiplq2

goqiplq23#

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

cartItemsList = "null" and not cartItemsList = null

所以,在检查之前,你要么从字符串“null”中删除双引号:

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

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

if (cartItemsList != "null")
fiei3ece

fiei3ece4#

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

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

相关问题