[英]How do I fix this javascript foreach bug?
I have an object in the form of我有一个对象的形式
res = { 2019:
[
{id: 1, points: 435},
{id: 830, points: 230},
...
]
}
and an array seasons which is just a bunch of years => ["2015","2016",..."2019"]和一个数组季节,它只是一堆年份 => ["2015","2016",..."2019"]
seasons.forEach(season => {
res[season].forEach(item => {
console.log(item);
});
});
The snipped above logs each result correctly however I still get this error: Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined上面的截图正确记录了每个结果,但我仍然收到此错误:未处理的拒绝(TypeError):无法读取未定义的属性“forEach”
Sometimes your object can be undefined
so you should verify if the key exist:有时您的对象可能
undefined
因此您应该验证密钥是否存在:
const ob = res = { 2015: [{ id: 1, points: 435 }, { id: 830, points: 230 }, ], 2019: [{ id: 1, points: 435 }, { id: 830, points: 230 }, ] } const seasons = ["2015", "2016", "2019"] seasons.forEach(season => { if (res[season]) { res[season].forEach(item => { console.log(item); }); } });
You could use optional chaining to easily solve this.您可以使用可选链来轻松解决此问题。 Simply add a question mark before the nested
forEach
, like this:只需在嵌套的
forEach
之前添加一个问号,如下所示:
seasons.forEach(season => {
res[season]?.forEach(item => {
console.log(item);
});
});
Note: As mentioned in the compatibility section of the linked doc, optional chaining is not yet supported by all browsers, so you might want to use a transpiler (like Babel)注意:如链接文档的兼容性部分所述,所有浏览器尚不支持可选链接,因此您可能需要使用转译器(如 Babel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.