语法错误:JSON 分析错误:"function"意外的标识符



第一次发布。我一直在寻找答案,但似乎可以找到任何可行的解决方案。我正在调试我在 ES6 中构建的购物车。它似乎在Chrome上完美运行,但在Safari和Firefox上,我遇到了错误。

Safari 中的错误:

SyntaxError: JSON Parse error: Unexpected identifier "function"

火狐中的错误:

SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data[Learn More]

我的代码:

export default class productUtil{
    constructor (){
    }
    addToCart (sku, price){
        let product={price, quantity:1};
        if (sessionStorage.getItem(sku) == undefined){
            sessionStorage.setItem(sku, JSON.stringify(product));
        }
        else {
            let oldValue=JSON.parse(sessionStorage.getItem(sku, product)); 
            let newValue = oldValue.quantity + 1;
            product.quantity = newValue;
            sessionStorage.setItem(sku,JSON.stringify(product));
        }
        this.cartBuilder(sku, product);
    }

    cartBuilder(sku, product){
        document.getElementById('listItems').innerHTML="";
        if (sessionStorage){
            for(let key in sessionStorage){
                let cartItem = document.createElement("div");
                cartItem.setAttribute("id","itemRows");
                product = JSON.parse(sessionStorage[key]);
                let totalPrice = product.price*product.quantity;
                cartItem.innerHTML=(
                        '<div>'+key+'</div>'+
                        '<input class="cart_input_size" id="'+key+'" type="number" value="'+product.quantity+'">'+
                        '<div>'+'$'+product.price+'</div>');
                document.getElementById('listItems').appendChild(cartItem);
            }   
        }
    }
}

谢谢,感谢任何帮助!

您也在迭代原型。使用 Object#hasOwnProperty() 检查它是原型属性还是可枚举属性

尝试

for(let key in sessionStorage){
  if(sessionStorage.hasOwnProperty(key)){
    // process storage item
  }
}

最新更新