简体   繁体   中英

SyntaxError: JSON Parse error: Unexpected identifier “function”

First time posting. I have been looking all over for an answer but can seem to find any working solution. I am debugging a shopping cart I built in ES6. It seems to work flawlessly on Chrome but on Safari and Firefox I have been getting an error.

Error in Safari:

SyntaxError: JSON Parse error: Unexpected identifier "function"

Error in Firefox:

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

My code:

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

Thank you, appreciate any help!

You are iterating the prototype also. Use Object#hasOwnProperty() to check if it is prototype or enumerable property

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM