Javascript 无法读取 null 的属性推送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26273043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot read property push of null
提问by forgottofly
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
当第一次将一个元素推送到一个为空的子数组时,我收到这个错误“无法读取 null 的属性推送”但是元素被推送了,第二次我做的一切都很好。它被添加到数组
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:
group 包含数据,departmentList 是子数组,声明如下:
$scope.parentDepartment = [
{
departmentsList: [{}]
}
];
回答by dfsq
Well don't push to nonexistent array maybe? You can explicitly check if it's not null and create one if needed:
好吧,也许不要推送到不存在的数组?您可以明确检查它是否不为 null 并在需要时创建一个:
this.group.departmentsList = this.group.departmentsList || [];
this.group.departmentsList.push({
name: group.newCategoryName,
sortOrder: group.departmentsList.length,
type: "category"
});

