You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

访问RAWG API返回的response.json数组提取彩虹六号数据问题

问题原因

  • 你使用for...in遍历数组时,拿到的循环变量game是数组的下标字符串,不是数组内存储的游戏对象。你在判断game == 6后执行game[0]['id'],本质是对字符串'6'做下标取值,自然只能拿到字符6,无法访问游戏数据。
  • 目标游戏《Tom Clancy's Rainbow Six Siege》在results数组的下标为7的位置,你判断game == 6实际匹配的是下标为6的《Rayman Legends》,找错了目标条目。

解决方案

方案1:直接取下标(已知目标位置时使用)

如果确定返回结果里目标游戏固定在第7位,不需要循环,直接取下标即可:

fetch("https://api.rawg.io/api/games?key=[KEY]&developers=ubisoft", {
    method: 'GET'
})
.then(response => response.json())
.then(data => {
  const rainbowSix = data.results[7];
  console.log('游戏ID:', rainbowSix.id);
  console.log('游戏名称:', rainbowSix.name);
});

方案2:按名称匹配(更稳妥,兼容API返回顺序变动)

避免API后续调整返回顺序导致取错数据,直接按游戏名称过滤匹配:

fetch("https://api.rawg.io/api/games?key=[KEY]&developers=ubisoft", {
    method: 'GET'
})
.then(response => response.json())
.then(data => {
  const rainbowSix = data.results.find(item => item.name === "Tom Clancy's Rainbow Six Siege");
  if (rainbowSix) {
    console.log('游戏ID:', rainbowSix.id);
    console.log('游戏名称:', rainbowSix.name);
  } else {
    console.log('当前页未找到目标游戏,可请求下一页数据重试');
  }
});

内容的提问来源于stack exchange,提问作者Yusuf_M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:15:02