【问题标题】:Cannot read property 'push' of null Javascript Shopping Cart无法读取 null Javascript Shopping Cart 的属性“推送”
【发布时间】:2016-03-05 20:24:28
【问题描述】:

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

的错误

无法读取 null 的属性“push”

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

显示错误的部分是

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

任何帮助将不胜感激

【问题讨论】:

  • 当您在其上调用 push() 时,您的 cart 变量未定义。要么您需要定义它 (var cart = []),要么您需要确保定义它的位置在 addItem() 函数的范围内。如果您在调用 push() 之前添加以下行 ,您会在控制台中看到什么:console.log(cart)?
  • 我猜想当你执行cart = JSON.parse(localStorage.getItem("testCart")); 时本地存储中没有任何内容,所以cart 设置为null。
  • 谁能告诉我为什么我的分数下降了 2 分??

标签: javascript jquery arrays shopping-cart


【解决方案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】:

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

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

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

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

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

    【讨论】:

      【解决方案3】:

      我解决了代码的问题。我需要先保存购物车,然后才能加载它!

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

      【讨论】:

        猜你喜欢
        • 2014-12-04
        • 1970-01-01
        • 2020-04-26
        • 1970-01-01
        • 2022-01-16
        • 2021-01-19
        • 2016-06-11
        • 1970-01-01
        • 2021-10-31
        相关资源
        最近更新 更多