无法读取 null 的属性推送 [英] Cannot read property push of null

查看:26
本文介绍了无法读取 null 的属性推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次将元素推送到为空的子数组时,出现此错误无法读取 null 的属性推送"但是元素被推送了,第二次我做的一切都很好.它被添加到数组中

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 包含数据,departmentList 是子数组,声明如下:

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

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

推荐答案

好吧,也许不要推送到不存在的数组?您可以明确检查它是否不为 null 并在需要时创建一个:

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

这篇关于无法读取 null 的属性推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆