2016-09-16 119 views
1

我知道它似乎是重复的,但事实并非如此。没有什么工作,无论我尝试。无法将JSON对象推入数组

我在我的角度模块列表:

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。 任何想法是什么问题?

+0

你拼错数组的时候你”已经宣布了它。你在互联网上错过了我。 – Dan

+0

,因为我现在手写那部分,但它在代码 – Mocktheduck

+0

中是正确的,你能否给我们更多的代码?看起来你的函数没有权限访问this.checkedInterviews。 – JOSEFtw

回答

3

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); 
 
})();

你也想尝试:

​​

注意:你应该能够使用this如果这一切都是在相同的功能。这也应该在全球范围内发挥作用。我使用IIFE的唯一原因是将示波器分开了

以上添加的代码段包含两种情况。

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

+0

哇好吧我仍然得到错误,它不会让我添加一个空的json – Mocktheduck

+0

添加工作代码片段 – nikjohn

+0

This不回答这个问题。你刚刚创建了一个新的'checkedInterviews'(你拼错了:'checkedIntervews')对象'Array',并没有回答关于'this'对象的问题。为什么'this.checkedInterviews'等于'undefined'? – Hydro

0

如果他们在不同的功能,this在第二个功能是不同的对象。

2

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

在Angular模块中,您可以将this分配给某个变量,然后尝试从第二个函数访问它。

如:

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

现在在功能上,你应该使用访问:

vm.checkedInterviews.push();

+0

这种方式可能会导致内存泄漏。所以你最好仔细处理。 – Han

+0

你说得对,他们在不同的范围 – Mocktheduck

0

试试这个 Here is working fiddle

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