简体   繁体   English

TypeError:无法在addItemToCart读取null的属性“ push”

[英]TypeError: Cannot read property 'push' of null at addItemToCart

i already tried searching throughout the forum and suggested posts but not quite what im looking for. 我已经尝试在整个论坛中搜索并建议帖子,但不是我想要的。

The issue is: When clicking on the list item, i get the error mentioned on title specifically in the cart.push(item); 问题是:单击列表项时,我在cart.push(item);得到标题上提到的错误cart.push(item); which is inside the function addItemToCart . addItemToCart函数内部。 which i've found is caused by not declaring the array, but i believ ei have declared it already. 我发现是由于未声明数组引起的,但我相信ei已经声明了它。

The question is: Am i correctly declaring the scope of my array variable? 问题是:我是否正确声明了数组变量的范围? Or is my problem regarding some other matter? 还是我在其他问题上有问题?

This is the html part: 这是html部分:

 <div>
    <ul>
        <li><a class="add-to-cart" href="#" data-name="Apple" data-price="1.99">Product1</li>
    </ul>
</div>

This html part gets referenced inside the script through the next click function : 该html部分通过next click函数在脚本内被引用:

        $(".add-to-cart").click(function(event){
            event.preventDefault(); // --> Prevents page from refreshing
            var name = $(this).attr("data-name");
            var price = Number($(this).attr("data-price"));

            addItemToCart(name, price, 1);

        });

This part here is where i declare both my variables at the beginning of the JS script: 这部分是在JS脚本的开头声明两个变量的地方:

        var cart = [];
        var Item = function(name, price, count){
            this.name = name
            this.price = price
            this.count = count
        };

And this part here is also inside of my script and belongs to the function i want to execute: 这部分也位于我的脚本内,属于我要执行的功能:

function addItemToCart(name, price, count){
    for (var i in cart){
        if (cart[i].name === name){
            cart[i].count += count;
            //cart[i].count += count;
            return;
        }
    }
    var item = new Item(name, price, count);
    cart.push(item);
    saveCart();
}

3 last parts of code are inside my <scope> </scope> 最后3个代码部分位于我的<scope> </scope>

Thanks in advance for any help i could recieve to solve the issue. 在此先感谢您提供的任何帮助,我都可以解决该问题。

You did not define cart in the main scope. 您没有在主范围中定义购物车。 You must define cart in a scope that is a parent of the addItemToCart function scope. 您必须在作为addItemToCart函数作用域父级的作用域中定义购物车。

Another alternative is to use 另一种选择是使用

window.cart = [];

Or for node.js 或对于node.js

global.cart = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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