无法读取空 Javascript 购物车的 属性 'push'

Cannot read property 'push' of null Javascript Shopping Cart

我已经休息了关于如何使用 javascript 构建购物车的在线教程,现在当我想将第一个项目添加到购物车时遇到错误。 我得到

的错误

无法读取 属性 'push' of null

并且代码正在尝试将项目添加到购物车数组列表 我尝试调试代码,我可以看到数组中有值,但仍然出现错误

显示错误的部分是

// add item to the cart with name , price , count 
    function addItem(name , price , count)
    {
        for (var i in cart)// loop the cart 
        {
            if (cart[i].name === name)// check the name we want to enter with the name in cart
                {
                    cart[i].count += count;
                    return;
                }
        }
        var item = new Item (name , price , count);

        alert(item);
        console.log(item);
        cart.push (item);// **getting an error in here** 
        saveCart ();

    }

完整代码是:

<html>
<head>
    <title>Shopping Cart</title>
    <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
  <h1>Shopping Cart</h1>  
    <div>
        <ul>
            <li><a class ="addtoCart" href="#" data-name="apple" data-price="1.22">Apple</a></li>
            <li><a class ="addtoCart" href="#" data-name="orange" data-price="2.22">Orange</a></li>
            <li><a class ="addtoCart" href="#" data-name="banana" data-price="3.22">Banana</a></li>
            <li><a class ="addtoCart" href="#" data-name="kiwi" data-price="4.22">Kiwi</a></li>
        </ul>
        <button id="cleareCart">Clear Cart</button>
    </div>
    <div>
        <ul id="showCart"></ul>

    </div>
<script>
    //jQuery 
    $(".addtoCart").click(function(event)
        { 
            event.preventDefault();
            var name = $(this).attr("data-name");
            var price = Number($(this).attr("data-price"));
            addItem(name , price, 1);
            displayCart();
        }                                            
    );
    function displayCart ()
    {
        var CartArray = listCart ();
        var outPut = "";
        for (var i in CartArray)
            {
                outPut += "<li>"+CartArray[i].name+" "+ CartArray[i].count+"</li>"
            }
        $("#showCart").html(outPut);
    }

    //******************************************Javascript/// shopping cart functions 
var cart =[];// this is array that contain all the shopping cart item
    // we need to display:
    /*name ,price,count, id */
    var Item =function (name , price , count)// add item to the cart array 
    {
        this.name = name
        this.price = price
        this.count = count
    }
    /*Cart Functions : what are cart need to do 

     load the cart ()// load from localstorage 
    */
    // add item to the cart with name , price , count and id of the item
    function addItem(name , price , count)
    {
        for (var i in cart)// loop the cart 
        {
            if (cart[i].name === name)// check the name we want to enter with the name in cart
                {
                    cart[i].count += count;
                    return;
                }
        }
        var item = new Item (name , price , count);

        alert(item);
        console.log(item);
        cart.push (item);
        saveCart ();

    }
    //remove the item from the cart with name, price , count , id  (one item only)
    function removeItemFromCart (name, count)
    {
        for (var i in cart)// loop the cart
            {
                if (cart[i].name === name)// check the name of the item with the item in cart
                    {
                        cart[i].count = cart[i].count-count;
                        if (cart[i].count === 0 )
                            {
                               cart.splice(i,1);
                            }
                        break;
                    }
            }
        saveCart ();
    }
    //remove the item from cart all (name) this will remove all of the item name
    function removeAllItem (name)// remove all of the one item from cart (if the count is more than one )
    {
        for (var i in cart)// loop the cart
            {
                if (cart[i].name === name)// check the name of the item with the item in cart
                    {
                        cart.splice(i,1);
                        break;
                    }
            }
        saveCart ();
    }
    function clareCart ()// remove everything from the cart
    {
        cart = [];
        saveCart ();
    }
    function countCart ()// return the total cumber of the items in the cart
    {
        var totalCount = 0 ;
        for (var i in cart )
            {
                totalCount += cart[i].count; 
            }
        return totalCount;
    }
    function totalCartCost ()
    {
        var totalCost = 0 ;
        for (var i in cart )
            {
                totalCost += cart[i].price;
            }
        return totalCost;
    }
    function listCart ()//array of items  // array of the cart that we can use to generate HTML
    {
        var cartCopy = [];
        for (var i in cart)
            {
                var item = cart[i];
                var itemCopy = {};
                for (var p in item)
                    {
                        itemCopy[p] = item[p];
                    }
                cartCopy.push (itemCopy);
            }
        return cartCopy;
    }
    function saveCart ()// localstorage 
    {
        localStorage.setItem("testCart", JSON.stringify(cart));
    }
    function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));
    }
    //addItem('', null , null );
   // addItem('apple',1.22 , 1);
   // addItem('apple',1.22 , 1);
   // addItem('apple',1.22 , 3);
   // addItem('orange',1.22 , 3);

    //console.log(cart);
   // console.log(cart);
    //removeAllItem('apple');
   // console.log(cart);
   // console.log (countCart()) ;

    //console.log (listCart());

    loadCart();
    var Array = listCart();
    console.log (Array);
    </script>
    </body>

任何帮助将不胜感激

我看了 5 天代码后发现了我自己的问题

  function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));

    }

load cart 正在尝试加载 Json 文件,但该文件尚不存在,因此没有 cart 所以它给我一个错误

为了解决这个问题,我添加了这个

        function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));
         if (cart === null) {
             cart = [];
            }
    }

您没有购物车数组。试试这个。为我工作。

<html>
<head>
    <title>Shopping Cart</title>
    <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
  <h1>Shopping Cart</h1>  
    <div>
        <ul>
            <li><a class ="addtoCart" href="#" data-name="apple" data-price="1.22">Apple</a></li>
            <li><a class ="addtoCart" href="#" data-name="orange" data-price="2.22">Orange</a></li>
            <li><a class ="addtoCart" href="#" data-name="banana" data-price="3.22">Banana</a></li>
            <li><a class ="addtoCart" href="#" data-name="kiwi" data-price="4.22">Kiwi</a></li>
        </ul>
        <button id="cleareCart">Clear Cart</button>
    </div>
    <div>
        <ul id="showCart"></ul>

    </div>
<script>
    //jQuery 
    $(".addtoCart").click(function(event)
        { 
            event.preventDefault();
            var name = $(this).attr("data-name");
            var price = Number($(this).attr("data-price"));
            addItem(name , price, 1);
            displayCart();
        }                                            
    );
    function displayCart ()
    {
        var CartArray = listCart ();
        var outPut = "";
        for (var i in CartArray)
            {
                outPut += "<li>"+CartArray[i].name+" "+ CartArray[i].count+"</li>"
            }
        $("#showCart").html(outPut);
    }

    //******************************************Javascript/// shopping cart functions 
var cart =[];// this is array that contain all the shopping cart item
    // we need to display:
    /*name ,price,count, id */
    var Item =function (name , price , count)// add item to the cart array 
    {
        this.name = name
        this.price = price
        this.count = count
    }
    /*Cart Functions : what are cart need to do 

     load the cart ()// load from localstorage 
    */
    // add item to the cart with name , price , count and id of the item
    function addItem(name , price , count)
    {
        if(cart == null)
            cart = [];
        for (var i in cart)// loop the cart 
        {
            if (cart[i].name === name)// check the name we want to enter with the name in cart
                {
                    cart[i].count += count;
                    return;
                }
        }
        var item = new Item (name , price , count);

        alert(item);
        console.log(item);
        cart.push (item);
        saveCart ();

    }
    //remove the item from the cart with name, price , count , id  (one item only)
    function removeItemFromCart (name, count)
    {
        for (var i in cart)// loop the cart
            {
                if (cart[i].name === name)// check the name of the item with the item in cart
                    {
                        cart[i].count = cart[i].count-count;
                        if (cart[i].count === 0 )
                            {
                               cart.splice(i,1);
                            }
                        break;
                    }
            }
        saveCart ();
    }
    //remove the item from cart all (name) this will remove all of the item name
    function removeAllItem (name)// remove all of the one item from cart (if the count is more than one )
    {
        for (var i in cart)// loop the cart
            {
                if (cart[i].name === name)// check the name of the item with the item in cart
                    {
                        cart.splice(i,1);
                        break;
                    }
            }
        saveCart ();
    }
    function clareCart ()// remove everything from the cart
    {
        cart = [];
        saveCart ();
    }
    function countCart ()// return the total cumber of the items in the cart
    {
        var totalCount = 0 ;
        for (var i in cart )
            {
                totalCount += cart[i].count; 
            }
        return totalCount;
    }
    function totalCartCost ()
    {
        var totalCost = 0 ;
        for (var i in cart )
            {
                totalCost += cart[i].price;
            }
        return totalCost;
    }
    function listCart ()//array of items  // array of the cart that we can use to generate HTML
    {
        var cartCopy = [];
        for (var i in cart)
            {
                var item = cart[i];
                var itemCopy = {};
                for (var p in item)
                    {
                        itemCopy[p] = item[p];
                    }
                cartCopy.push (itemCopy);
            }
        return cartCopy;
    }
    function saveCart ()// localstorage 
    {
        localStorage.setItem("testCart", JSON.stringify(cart));
    }
    function loadCart ()// load the cart 
    {
        cart = JSON.parse(localStorage.getItem("testCart"));
    }
    //addItem('', null , null );
   // addItem('apple',1.22 , 1);
   // addItem('apple',1.22 , 1);
   // addItem('apple',1.22 , 3);
   // addItem('orange',1.22 , 3);

    //console.log(cart);
   // console.log(cart);
    //removeAllItem('apple');
   // console.log(cart);
   // console.log (countCart()) ;

    //console.log (listCart());

    loadCart();
    var Array = listCart();
    console.log (Array);
    </script>
    </body>

我刚在第 60 行添加

if(cart == null)
    cart = [];

我修复了代码的问题。我需要保存购物车才能加载它!

    myList93.saveCart();
    myList93.loadCart();
    displayCart();