处理Reactjs .Reduce中的零值



当我搜索数组时,我会得到'typeError:无法读取属性'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,在这种情况下,这给出了例外

要在更安全的一面,您可以添加其他null检查val to to

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

并不是说category缺失,而是说outcome_status是null,并且试图从null读取category(显然不存在(。

简单的方法是确保val.outcome_status是一件事情:

checkArray(array) {
    var search = 'Find this';
    var count = array.reduce(function(n, val) {
         return n + (val.outcome_status && val.outcome_status.category && val.outcome_status.category === search)
    }, 0);
    return count; 
}

查看您的代码,使用filter()可能会更干净,然后返回其余的长度:

checkArray(array) {
    var search = 'Find this';
    return array.filter(val => val.outcome_status && val.outcome_status.category && val.outcome_status == search).length;
}

您没有检查val.outcome_status是null

尝试以下:

return n + (val.outcome_status && val.outcome_status.category && val.outcome_status.category === search)

这不是"类别"的问题。它显示错误,因为您正在尝试从notxitence键访问密钥(类别((atumection_status(。

因此,您应该检查键是否存在

您将通过'valcome_status'在val中做到这一点。或添加atumy_status作为所有对象的关键,并给出null值作为初始值。

最新更新