简体   繁体   中英

Difficulty with error “Uncaught TypeError: Cannot read property 'name' of undefined”

I've been working on a JavaScript code in order to make a checkout cart of a pizza, but have been having an issue with the showCart function.

let pizzas=[
{ name:"Pepperoni", img:"pizza.png", price:8.99}, 
{ name:"Alfredo", img:"pizza.png", price:9.99}, 
{ name:"Cheese", img:"cheese.png", price:7.99} 
];

function registerButtonEvents() 
{
    let buttons=document.getElementsByTagName("button");
    for(let i = 0; i < buttons.length-1; i++)
    {
        buttons[i].addEventListener("click", function() {
            addToCart(i);
        });
    }
    let number = localStorage.getItem("number");
    if(number == null)
        number = 0;
    document.getElementById("num").innerHTML = number;
}

function addToCart(pId)
{
    let cartJ = localStorage.getItem("cart");
    let cart;

    if(cartJ===null) //Cart is empty
    {
        cart=[];
    }
    else
    {
        cart=cartJ.split(",");
    }

    cart.push(pId);
    let number= localStorage.getItem("number");

    if(number===null)
        number = 0;

    document.getElementById("num").innerHTML = `${++number}`;
    localStorage.setItem("cart", cart.toString());
    localStorage.setItem("number", number);
}

function clearCart()
{
    localStorage.removeItem("cart");
    localStorage.removeItem("num");
}

function showCart() 
{
    let cartJ = localStorage.getItem("cart");
    let cart = [];
    let info = "";
    if(cartJ === null)
    {
        document.getElementById("myCart").innerHTML=`<h2>No items in cart!</h2>`;
    }
    else
    {
        cart = cartJ.split(","); 
        for (let i in cart)
        {
            let item = pizzas[cart[i]];
            info+=
                `<div class="row">
                    <div class="col-md-2 text-center">
                        <h3>${item.name}</h3>
                    </div>  
                    <div class="col-md-2 text-center">
                        <img class="pizza" src="./images/${item.img}" alt="pepperoni">
                    </div>
                    <div class="col-md-2 text-center">
                        <h3>${item.price}</h3>
                    </div>
                    <div class="col-md-2 text-center">
                        <button type="button" class="btn btn-primary" onclick="removePizza(${i})">Remove</button>
                    </div>
                </div>
                `;
        }
        document.getElementById("myCart").innerHTML=info;
    }
}


function removePizza(piz)
{
    var cart = localStorage.getItem("cart");
    cart = cart.split(",");
    cart.splice(piz, 1);
    if (cart.length == 0)
        clearCart();
    else
    {
        localStorage.setItem("cart", cart);
        localStorage.setItem("number",cart.length);
    }
    showCart();
}

Developer tools tell me that the error is in the line in:

let item = pizzas[cart[i]];

but I don't necessarily understand why. If anyone could send some feedback it would be greatly appreciated.

The problem is when you access <h3>${item.name}</h3> . Your item is undefined there because your cart ( cart = cartJ.split(","); ) probably stores some strings like "Pepperoni" (as you split them using a comma) and after that you want to access the pizzas array using one of those strings instead of an index.

披萨

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