当我搜索数组时出现“TypeError: Cannot read property 'category' of null”,不是数组中的所有项目都有这个字段,但我的代码应该只查看它是否不为空,不是吗?
checkArray(array) {
var search = 'Find this';
var count = array.reduce(function(n, val) {
return n + (val.outcome_status.category && val.outcome_status.category === search)
}, 0);
return count;
}
最佳答案
您只需要为 val.outcome_status 添加 null 检查,它也可能为 null,在这种情况下会出现异常
为了安全起见,您也可以为 val 添加一个额外的 null 检查
checkArray(array) {
var search = 'Find this';
var count = array.reduce(function(n, val) {
return n + (val && val.outcome_status && val.outcome_status.category && val.outcome_status.category === search)
}, 0);
return count;
}
关于javascript - 处理 reactjs .reduce 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933286/