如何读取IGDB API返回对象中release_dates数组的首个元素?
问题解决:访问IGDB API游戏发布日期时的TypeError错误
报错原因
你遇到的TypeError: Cannot read properties of undefined (reading '0'),本质是部分游戏对象的release_dates属性不存在(值为undefined),或是为空数组,直接通过collection.release_dates[0]访问会触发错误。
虽然你提供的示例数据里release_dates是正常数组,但IGDB API返回的实际数据中,可能存在部分游戏未填写发布日期的情况,导致该字段缺失或为空。
修复代码
在访问release_dates[0].human之前,先做安全校验,确保release_dates是存在的数组且包含元素:
const collections = response.data; collections.forEach(collection => { console.log(collection.name); // 安全校验:确认release_dates存在、是数组且非空 if (collection.release_dates && Array.isArray(collection.release_dates) && collection.release_dates.length > 0) { console.log(collection.release_dates[0].human); } else { console.log('该游戏无可用发布日期'); } });
额外处理方案
如果需要更严谨的逻辑,可以参考以下两种方式:
- 提前过滤掉无有效发布日期的游戏:
const validCollections = collections.filter(collection => collection.release_dates && Array.isArray(collection.release_dates) && collection.release_dates.length > 0 ); validCollections.forEach(collection => { console.log(collection.name, collection.release_dates[0].human); }); - 若要获取特定地区的发布日期,可以在
release_dates数组中筛选(比如根据API返回的region字段),而不是直接取第一个元素。
内容的提问来源于stack exchange,提问作者Sami
相关产品推荐
相关产品推荐

