【问题标题】:"Object doesn't support property or method 'push'" [duplicate]“对象不支持属性或方法'push'” [重复]
【发布时间】:2014-10-08 17:18:18
【问题描述】:

我正在尝试向 AngularJS 中的现有 JSON 对象添加新值,但收到以下错误消息:

"Object doesn't support property or method 'push'"

这是我的代码:

$scope.addStatus = function (text) {          
          $scope.application.push({ 'status': text }); //I have tried 'put' but getting the error
      };

 $scope.create = function( application ){
        $scope.addStatus('Under review');
 }

这是我的应用程序 json 的样子:

{"type":"Not completed","source":"mail","number":"123-23-4231","amount":"234.44","name":"John ","id":"123","by_phone":true}

我想在上面的 json 中附加/添加状态,添加 status 属性后的样子:

{"type":"Not completed","source":"mail","number":"123-23-4231","amount":"234.44","name":"John ","id":"123","by_phone":true, "status": "under review"}

【问题讨论】:

  • $scope.application 定义在哪里?如果它不是一个数组,那么你的代码将会失败。
  • @psl:你怎么把它标记为重复的?需要解释一下吗?
  • 因为如果您阅读答案,您就会知道。只是措辞不同。您至少应该努力找出错误消息的含义,首先是(而不是从问题中的控制台粘贴错误)......对不起,我认为它不可能不是复制。希望这能解释。

标签: javascript angularjs angularjs-scope


【解决方案1】:

.push() 是一个 JS 数组的方法。

但应用程序只是一个对象(不是数组)。在这里我们可以使用:

// instead of this
// $scope.application.push({ 'status': text });
// use this
$scope.application.status = text;

【讨论】:

    【解决方案2】:

    Array.prototype.push 仅适用于数组。通过以下方式之一添加属性:

    $scope.application['status'] = text;
    

    或者:

    $scope.application.status = text;
    

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2014-07-29
      • 2019-07-05
      相关资源
      最近更新 更多