处理reactjs .reduce中的空值

时间:2018-02-22 17:05:08

标签: javascript arrays reactjs

我得到'TypeError:当我搜索一个数组时,无法读取null'属性'类'',而不是数组中的所有项都有这个字段,但是我的代码应该只看它是否为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; 
}

5 个答案:

答案 0 :(得分:1)

你只需要为 val.outcome_status 添加null检查,它也可能为null,在这种情况下给出例外

为了更加安全,您可以添加额外的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; 
}

答案 1 :(得分:0)

您没有检查val.outcome_status是否为空

答案 2 :(得分:0)

它没有说category缺失,它说outcome_status为空并且它试图从空读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;
}

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

这不是“类别”的问题。它显示错误,因为您尝试从非密钥(outcome_status)访问密钥(类别)。

所以你应该检查密钥是否存在

你可以通过val'中的'“outcome_status”来做到这一点。 或者将outcome_status添加为所有对象的键,并将null值作为初始值。