【问题标题】:Cannot read property 'push' of undefined Javascript [duplicate]无法读取未定义 Javascript 的属性“推送”[重复]
【发布时间】:2015-08-01 17:54:37
【问题描述】:

您好,好像我无法推动我的阵列? 代码:

  $scope.arrResult = [];
  dpd.timesheets.get( function (result) {
    console.log(result);

    for (i = 0, n = result.length; i < n; i++) {
      var item = result[i];
      $scope.arrResult[item.week].push(item);
    }
    console.log($scope.arrResult);

  });

我收到此控制台错误

Uncaught TypeError: Cannot read property 'push' of undefined

如果我设置$scope.arrResult[item.week].push(item); to $scope.arrResult[item.week] = item; 它可以正常工作 但我需要/想推,怎么了?

【问题讨论】:

    标签: javascript arrays angularjs


    【解决方案1】:

    这是因为

    $scope.arrResult[item.week]
    

    它本身不是一个数组。

    push() 属于Array.prototype

    要明白我的意思,请尝试

    $scope.arrResult[item.week] = [];
    

    $scope.arrResult[item.week] = new Array();
    

    然后试试push()

    【讨论】:

    • 我明白了,嗯.. 但是我该如何以正确的方式做到这一点,如果我在推送之前设置 = [],我只会在数组中得到一个对象,我想要所有 :)
    • @Stweet,你是​​什么意思'全部'。也许甚至不需要数组?
    • 结果包含很多对象,我希望这些对象在 $scope.arrResult[week] 中排序,例如。 $scope.arrResult[21] 包含第 21 周的所有对象
    • @Stweet,啊!使用 concat stackoverflow.com/questions/4156101/…
    • @Stweet 所以,如果 item 是一个数组,那么 $scope.arrResult[item.week].concat(item);
    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多