无法将JSON对象推入Array

Cannot push JSON object into Array

本文关键字:Array 对象 JSON      更新时间:2023-09-26

我知道它看起来像一个副本,但它不是。不管我怎么努力,都没用。

我有一个列表在我的angular模块:

this.checkedInterviews = []

,然后是一个函数:

var interviewModel = {
                        interviewId: self.pendingInterviews[i].id,
                        status: self.pendingInterviews[i].status,
                        location: self.pendingInterviews[i].location,
                        start: self.pendingInterviews[i].start,
                        hideCheck: null
                    };
 this.checkedInterviews.push(JSON.stringify(interviewModel));

得到Cannot read property 'push' of undefined。知道是什么问题吗?

var checkedIntervews = []
var interviewModel = {};
checkedIntervews.push(JSON.stringify(interviewModel));
console.log(checkedIntervews);
(function arrayPush() {
this.checkedIntervews = [];
var interviewModel = {};
this.checkedIntervews.push(JSON.stringify(interviewModel));
console.log(this.checkedIntervews);
})();

你想试试:

var checkedIntervews = []
var interviewModel = {};
checkedInterviews.push(JSON.stringify(interviewModel));
$scope.checkedInterviews = checkedInterviews; //If using AngularJS because Angular is tagged in the question

注意:如果所有这些都在同一个函数中,您应该能够使用this。这也应该在全局范围内工作。我使用IIFE的唯一原因是将作用域

分开。

以上两种情况下添加的代码片段。

如果不清楚this是什么在你的问题。

如果它们放入不同的函数,则第二个函数中的this是不同的对象。

看来,第二个功能是使用不同的this

在Angular Module中,你可以将this赋值给某个变量,然后尝试从第二个函数中访问它。

例如:

var vm = this;
vm.checkedInterviews = [];

现在在函数中,你应该使用:

vm.checkedInterviews.push();

试试这个这里是工作小提琴

  var myApp = angular.module('myApp',[]);
  function MyCtrl($scope) {
  $scope.checkedInterviews = [];
  $scope.pendingInterviews = [{'id':1,'status':'pending','location':'abc','start':'start'}];
  for(i= 0; i < $scope.pendingInterviews.length; i++){
      var interviewModel = {
                      interviewId: $scope.pendingInterviews[i].id,
                      status: $scope.pendingInterviews[i].status,
                      location: $scope.pendingInterviews[i].location,
                      start: $scope.pendingInterviews[i].start,
                      hideCheck: null
      };
      console.log(interviewModel);
      $scope.checkedInterviews.push(JSON.stringify(interviewModel));
    }
  console.log($scope.checkedInterviews);
}