簡體   English   中英

SyntaxError:JSON解析錯誤:意外的標識符“功能”

[英]SyntaxError: JSON Parse error: Unexpected identifier “function”

第一次發布。 我一直在尋找答案,但似乎可以找到任何可行的解決方案。 我正在調試我在ES6中構建的購物車。 它似乎可以在Chrome上完美運行,但是在Safari和Firefox上卻出現錯誤。

Safari中的錯誤:

SyntaxError: JSON Parse error: Unexpected identifier "function"

Firefox中的錯誤:

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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM