Cannot read property push of null

半世苍凉 提交于 2020-01-14 07:49:07

问题


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: [{}]
    }
];

回答1:


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


来源:https://stackoverflow.com/questions/26273043/cannot-read-property-push-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!