admin管理员组

文章数量:1189386

while pushing an element for the first time to a child array which is null,I'm getting this error "Cannot read property push of null" But the element gets pushed,and the second time I do everything goes fine.It gets added to the array

this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});

group contains the data and departmentList is the child array which is declared like this:

 $scope.parentDepartment = [
    {
        departmentsList: [{}]
    }
];

while pushing an element for the first time to a child array which is null,I'm getting this error "Cannot read property push of null" But the element gets pushed,and the second time I do everything goes fine.It gets added to the array

this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});

group contains the data and departmentList is the child array which is declared like this:

 $scope.parentDepartment = [
    {
        departmentsList: [{}]
    }
];
Share Improve this question edited Oct 9, 2014 at 7:53 dfsq 193k26 gold badges242 silver badges259 bronze badges asked Oct 9, 2014 at 7:50 forgottoflyforgottofly 2,71912 gold badges54 silver badges96 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 25

Well don't push to nonexistent array maybe? You can explicitly check if it's not null and create one if needed:

this.group.departmentsList = this.group.departmentsList || [];
this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});

本文标签: javascriptCannot read property push of nullStack Overflow