【问题标题】:array.push is not a functionarray.push 不是一个函数
【发布时间】:2016-10-03 11:46:54
【问题描述】:

我想使用以下代码在 Javascript 中的数组中添加一个新值:

$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);
    }
}

但是当我想通过“addToShoppingCart”函数将新产品添加到数组中时,我收到了$rootScope.shoppingCart.push is not a function 错误。 我的眼睛我没有任何问题,因为我想将一个数组推入一个数组,但它一直伴随着这个错误。

有没有人看到我在这里做错了什么?

【问题讨论】:

  • 代码看起来不错,也许你在代码的其他地方覆盖了 shoppingCart?
  • 与您在此代码中遇到的错误没有任何关系。这只是意味着$rootScope.shoppingCart 不是数组的实例,或者可能在代码的其他部分中重新分配。
  • 您可能在此函数调用之前将$rootScope.shoppingCart 作为对象或其他数据类型
  • 试试 if (!angular.isArray($rootScope.shoppingCart)) console.log($rootScope.shoppingCart);之前 $rootScope.shoppingCart.push(product);
  • @NVO 不,你不应该那样做。而是确保 response.data 在覆盖属性时是一个数组

标签: javascript angularjs arrays


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 2020-08-24
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2017-04-24
    相关资源
    最近更新 更多