简体   繁体   中英

array.push is not a function

I want to add a new value to a array in Javascript with the following code:

$rootScope.shoppingCart = new Array();

$rootScope.addToShoppingCart = function(item){
    var quantity = 1;
    var product = [];

    for(var i=0; i< $rootScope.shoppingCart.length; i++){
        if($rootScope.shoppingCart[i].productNumber.indexOf(item.product.productNumber) > -1){
            quantity = $rootScope.shoppingCart[i].quantity+1;
            $rootScope.shoppingCart[i].quantity = quantity;
            break;
        }
    }
    if(quantity == 1){
        product = {
            name: item.product.brandName + " "+ item.product.productNumber,
            price: item.price,
            image: item.product.image1,
            quantity: quantity,
            productNumber: item.product.productNumber,
            productId: item.product._id
        };
        $rootScope.shoppingCart.push(product);
    }
}

But when I want to add a new product to the array via the ' addToShoppingCart ' function I get an $rootScope.shoppingCart.push is not a function error. I my eyes I do not anything wrong because I want to push an array into an array, but it keeps coming with this error.

Is there anybody who sees what I'm doing wrong here?

您可以简单地将以下代码添加到“loadcart”函数中

Array.prototype.push.apply($rootscope.shoppingCart, response.data)

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