javascript - 未捕获的类型错误:在 null
问题描述
我正在使用 ajax 在我的页面中获取表格格式。问题是它正在工作,目前我遇到了这个问题
我的代码
$.each(res,function(index,row){
console.log(row.bookable);
//{id: 2, slug: "dire_international_queen", organization_id: 1, roomtype_id: 5, no_bed: "2", …}
console.log(row.bookable.slug); // it show what i expect (working), but **"Uncaught TypeError: Cannot read property 'slug' of null"**
}
错误
未捕获的类型错误:无法读取 null 的属性“slug”
解决方案
你正在使用每个所以我想你在 ajax 响应中得到数组结果。在这里检查两件事。
(row.bookable !=null) and (row.bookable.slug !=null)
它通常发生是因为您为“可预订”属性获得了一些 null 值
$.each(res,function(index,row){
if(row.bookable!=null)
{
console.log(row.bookable);
}
//{id: 2, slug: "dire_international_queen", organization_id: 1, roomtype_id: 5, no_bed: "2", …}
//check here
if(row.bookable !=null && row.bookable.slug!=null)
console.log(row.bookable.slug);
})