无法读取未定义 Javascript 的属性“推送”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30350445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:02:58  来源:igfitidea点击:

Cannot read property 'push' of undefined Javascript

javascriptarraysangularjs

提问by Stweet

Hi it seams like i can't push my array ? code:

嗨,接缝好像我不能推动我的阵列?代码:

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

  });

i get this console error

我收到此控制台错误

Uncaught TypeError: Cannot read property 'push' of undefined

if i set $scope.arrResult[item.week].push(item); to $scope.arrResult[item.week] = item;it works with no error but i need / want to push, whats wrong ?

如果我设置$scope.arrResult[item.week].push(item); to $scope.arrResult[item.week] = item;它没有错误,但我需要/想要推送,怎么了?

回答by AmmarCSE

This is because

这是因为

$scope.arrResult[item.week]

itself is not an array.

本身不是数组。

push()is of Array.prototype

push()Array.prototype

To see what I mean, try

要明白我的意思,请尝试

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

or

或者

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

and then try push()

然后尝试 push()