无法读取属性推送null

时间:2014-10-09 07:50:08

标签: javascript arrays angularjs-scope

在第一次将元素推送到null数组的子数组时,我收到此错误 "无法读取属性推送null" 但元素被推,第二次我做的一切都很好。它被添加到数组

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

group包含数据,departmentList是子数组,声明如下:

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

1 个答案:

答案 0 :(得分:8)

不要推送到不存在的阵列吗?您可以明确检查它是否为空,并在需要时创建一个:

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