类型错误:无法读取未定义的 JavaScript 属性“推送”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29529574/
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 03:30:56  来源:igfitidea点击:

TypeError: Cannot read property 'push' of undefined, JavaScript

javascriptjqueryangularjs

提问by rksh

I'm working in this Angular project where user submits a comment form, and the new comment is added to the comments that's already posted. Here is my code.

我在这个 Angular 项目中工作,用户提交一个评论表单,新评论被添加到已经发布的评论中。这是我的代码。

.controller('productCtrl', function($scope, $http, $routeParams, Page){
$scope.product = {};
$scope.review = {};
$scope.comments = {};

routeparm = $routeParams.param;

$scope.review = function(){
    var review_box = $scope.review_form.review_box;

    $http.post('./comment.php', {
        comment : review_box,
        code: routeparm
    })

    .success(function(data){
            $scope.comments.push(data.comments);
            $scope.review.review_box = '';
    })

    .error(function(data){
        $scope.has_error = true;
        $scope.error_message = data;
    })

};

However when I try to add a comment I get the following error.

但是,当我尝试添加评论时,出现以下错误。

TypeError: Cannot read property 'push' of undefined

I've defined an empty $scope.comments = {}; so why am I getting this error? And how can I fix it? Thanks

我定义了一个空的 $scope.comments = {}; 那么为什么我会收到此错误?我该如何解决?谢谢

回答by Sajeetharan

The comments you have declared is an Object. Just change your declaration to an array ,

您声明的注释是一个对象。只需将您的声明更改为数组,

From:

从:

$scope.comments = {};

To:

到:

$scope.comments = [];

EDIT:If you need to Push new Object, You need to make your Comments as Array of Object like this and push the new Object

编辑:如果您需要推送新对象,您需要像这样将您的评论作为对象数组并推送新对象

$scope.comments = { 
    1: {name:'',review:'',comment:'',uptime:'',gravatar:''}
}

 $scope.comments.push({name:'rukshi', review:'test comment',comment:'yet another comment',uptime:'',gravatar:''});

回答by Masum Billah

You may try this

你可以试试这个

.controller('productCtrl', function($scope, $http, $routeParams, Page){
  $scope.product = {};
  $scope.review = {};
  $scope.comments = [];

  routeparm = $routeParams.param;

  $scope.review = function(){
  var review_box = $scope.review_form.review_box;

$http.post('./comment.php', {
    comment : review_box,
    code: routeparm
}).success(function(data){
        $scope.comments.push(data.comments);
        $scope.review.review_box = '';
}).error(function(data){
    $scope.has_error = true;
    $scope.error_message = data;
})

};