使用JS的reduce方法时报Cannot read property 'others' of undefined错误如何解决
报错原因及修复方案
报错原因
- Filter逻辑存在漏洞:你使用的过滤条件
d["1"]?.others !== ""中,当对象不存在"1"属性时,d["1"]?.others返回undefined,undefined !== ""的判断结果为true,因此没有"1"属性的元素(比如示例数据中的Person6)会被保留进others1数组。 - Reduce回调的属性访问遗漏可选链:你在赋值语句右侧的
a[c["1"].others]没有给c["1"]加可选链运算符?.,当遍历到没有"1"属性的元素时,c["1"]为undefined,访问c["1"].others就会抛出Cannot read property 'others' of undefined的错误。
修复方案
步骤1:修正filter过滤逻辑
过滤时先判断"1"属性是否存在,再判断others不为空,确保进入others1的元素都有符合要求的"1"属性:
const others1 = data.filter((d) => d["1"] && d["1"].others !== "");
步骤2:统一reduce内的属性访问写法
给所有c["1"]访问都加上可选链,即使有异常元素也不会直接报错:
let red = [...others1].reduce( (a, c) => ( (a[c["1"]?.others] = (a[c["1"]?.others] || 0) + 1), a ), {} );
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

