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

JavaScript fetch获取数组型API响应时无法正确读取字段值

问题原因

接口响应解析后最外层是数组结构,不是普通键值对对象,直接在数组实例上访问example属性会得到undefined,自然无法读取到目标值。
接口返回的结构参考:

[
  {
    "example": "true"
  }
]
基础修复方案

数组需要先通过下标索引取出内部的对象元素,再访问对象上的example字段。如果接口固定返回仅包含一个对象的数组,直接取下标为0的元素即可,修正后的代码如下:

.then(res => res.json())
.then(json => {
  console.log(json[0].example)
})
兼容优化写法

如果无法保证接口永远返回非空数组,可以增加校验逻辑避免运行报错:

.then(res => res.json())
.then(json => {
  let exampleValue = undefined;
  if (Array.isArray(json) && json.length > 0) {
    exampleValue = json[0].example;
  }
  console.log(exampleValue);
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 14:57:29