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

时间:2016-03-05 20:24:28

标签: javascript jquery arrays shopping-cart

我已经完成了关于如何使用javascript构建购物车的在线教程,并且当我想将第一个项目添加到购物车时现在面临错误。 我得到了<错误

无法读取属性'push'为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>

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

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

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

    }

load cart正在尝试加载它尚不存在的Json文件,然后没有购物车 所以它给我一个错误

修复我添加此

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

答案 1 :(得分:1)

你没有购物车阵列。试试这个。为我工作。

<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 = [];

答案 2 :(得分:1)

我用代码修复了问题。我需要在装载之前保存购物车!

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